字段“id”需要一个数字,但得到了<内置函数 id>

2023-12-13

我想在我的 django 应用程序中删除和编辑笔记,但我对这个错误感到震惊很长时间 错误 : ”/delete/1/ 处出现类型错误 字段“id”需要一个数字,但得到了。"

模型.py

from django.db import models
from django.utils import timezone

# Create your models here.
class Category(models.Model):
    name = models.CharField(max_length=100)

    class Meta:
        verbose_name = ("Category")
        verbose_name_plural = ("Categories")
    def __str__(self):
        return self.name

class ToDoList(models.Model):
    title = models.CharField(max_length=200)
    content = models.CharField(max_length=500)
    created_on = models.DateField(default=timezone.now().strftime("%Y-%m-%d"))
    due_date = models.DateField(default=timezone.now().strftime("%Y-%m-%d"))
    category = models.ForeignKey(Category,on_delete=models.DO_NOTHING,default="general")

    class Meta:
      ordering = ["-created_on"]
    def __str__(self):
        return self.title

class Note(models.Model):
    text = models.CharField(max_length=100)
    created = models.DateTimeField(auto_now_add = True)

    class Meta:
        verbose_name = ("Note")
    def __str__(self):
        return self.text

我的 todoapp/urls.py

urls.py

from django.contrib import admin
from django.urls import path, include
from todolist.views import index,note,del_note,edit_note


urlpatterns = [
    path('admin/', admin.site.urls),
    path('',index,name = 'ToDoList'),
    #path('',note,name = 'Note'),
    path('note/', note, name='Note'),
    path('delete/<note_id>/',del_note ,name = 'del_note'),
    path('edit/<note_id>/',edit_note,name='edit_note'),
]

我的待办事项/观点views.py

def del_note(request, note_id):

    x = Note.objects.get(id = id)
    print (x) // tried for degugging
    x.delete()
    return redirect("/")   


def edit_note(request, note_id):
    x = Note.objects.get( id = id)
    print (x)
    return redirect("/")

这是我的html注释.html

<body>
    <nav class="navbar navbar-inverse">
        <div class="container-fluid">
            <div class="navbar-header">
                <a class="navbar-brand" href="#">ToDo/Notes</a>
            </div>
            <ul class="nav navbar-nav">
                <li><a href="{% url 'ToDoList' %}">ToDoApp</a></li>
                <li class="active"><a href="{% url 'Note' %}">Notes</a></li>

            </ul>
        </div>
    </nav>

    <div class="container">
        <div class="content">
            <h1>Notes</h1>
            <p class="tagline">a Django Notes app</p>
            <form action="" method="POST">
                {% csrf_token %}
                <div class="inputContainer">
                    {{ form.as_p }}
                    <input type="submit" placeholder="Add a Note" value="Add note">
                </div>
            </form>

        </div>
    </div>
    <section class="section">
        <div class="container">
            <div class="row">

                {% for sticky in Notes %}
                <div class="col-md-3">
                    <div class="box">
                        <article class="media">
                            <div class="media-left">
                                <a href="{% url 'edit_note' sticky.id %}"
                                    <button class="glyphicon glyphicon-pencil">

                                    </button>
                                </a>
                            </div>
                            <div class="media-content">
                                <div class="content">
                                    <ul>

                                        <li>
                                            <p>{{sticky.text}}</p>
                                        </li>

                                    </ul>
                                </div>
                            </div>
                            <div class="media-right">
                                <a href="{% url 'del_note' sticky.id %}"
                                                    <button class="delete"></button>
                                                    </a>
                            </div>
                        </article>
                    </div>
                </div>
                {% endfor %}
            </div>
        </div>
    </section>
</body>

迁移文件0001_初始.py

# Generated by Django 3.0.3 on 2020-03-28 06:07

from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Category',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=100)),
            ],
            options={
                'verbose_name': 'Category',
                'verbose_name_plural': 'Categories',
            },
        ),
        migrations.CreateModel(
            name='Note',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('text', models.CharField(max_length=100)),
                ('created', models.DateTimeField(auto_now_add=True)),
            ],
            options={
                'verbose_name': 'Note',
            },
        ),
        migrations.CreateModel(
            name='ToDoList',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('title', models.CharField(max_length=200)),
                ('content', models.CharField(max_length=500)),
                ('created_on', models.DateField(default='2020-03-28')),
                ('due_date', models.DateField(default='2020-03-28')),
                ('category', models.ForeignKey(default='general', on_delete=django.db.models.deletion.DO_NOTHING, to='todolist.Category')),
            ],
            options={
                'ordering': ['-created_on'],
            },
        ),
    ]

here is my note app page enter image description here

so when i click on delete note i get below error enter image description here

您能否提供有关如何执行 edit_note 操作来编辑我的笔记的想法,提前致谢。


你需要在这里改变:

from django.shortcuts import render

def del_note(request, note_id):

    x = Note.objects.get(id = note_id)  # <-- Here
    print (x) // tried for degugging
    x.delete()
    return redirect("/")   


def edit_note(request, note_id):
    x = Note.objects.get( id = note_id) # <-- Here
    form = NoteForm(request.POST or None, instance=x)
    if request.method == "POST":
        if form.is_valid():
            form.save()
            return redirect("/")
    return render(request, 'edit_template.html', context={'form':form,'sticky':x})

 # edit_template.html
 <form action="{% url 'edit_note' sticky.id %}" method="POST">
      {% csrf_token %}
      <div class="inputContainer">
          {{ form.as_p }}
          <input type="submit" placeholder="Edit Note" value="Edit note">
      </div>
 </form>

发生错误是因为您通过了id,但你应该通过note_id反而。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

字段“id”需要一个数字,但得到了<内置函数 id> 的相关文章

随机推荐