Field 'id' expected a number but got <built-in function id>

Viewed 30124

i want to delete and edit notes in my django app, but i am struck on this error for long Error : "TypeError at /delete/1/ Field 'id' expected a number but got ."

models.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

my 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'),
]

my todolist/views 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("/")

here is my html note.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>

migration file 0001_intial.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

could you please give idea about how to perform edit_note operation to edit my note as well, Thanks in advance.

4 Answers

You need to change here:

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>

The error was occurring because you passed id, but you should pass note_id instead.

Please see this answer if you were playing with API(Rest Framework of Django) I got this error and I solved it by changing True to False while serializing the object.

@api_view(['GET'])
def event_detail(request, pk):
    try:
        event = Event.objects.get(id=pk)
        # This is the line I have made changes True to False.
        serializer = EventSerializer(event, many=False)
        return Response(serializer.data)
    except:
        return render(request, "404_page.html")

Got this same error and here's the solution for it,

reason of error: if your URL/API is very similar to a path that is working on id (like a detail page)

For ex: (in my case)

path('api/articles/', views.getArticles, name = "articles"),
path('api/articles/<str:pk>/', views.getArticleDetails, name = "article-details"),
path('api/articles/article-create/', views.createArticle, name = 'article-create')

Here the article creates page url (3rd url) will not work because of the detail url (2nd), as it is excepting an id and not a string.

The fix is to make it different from details article something like this

path('api/articles/', views.getArticles, name = "articles"),
path('api/articles/<str:pk>/', views.getArticleDetails, name = "article-details"),
path('api/article-create/', views.createArticle, name = 'article-create'),

You have to use note_id instead of id as below...

def del_note(request, note_id):
    x = Note.objects.get(id = note_id)
    # Your logic 


def edit_note(request, note_id):
    x = Note.objects.get(id = note_id)
    # Your logic

If you want to edit then you can do it like...

def edit_note(request, note_id):
    x = Note.objects.get(id = note_id)
    x.field_name_1 = new_val_1
    x.field_name_2 = new_val_2
    # and so on for other fields...
    x.save()


    # Your logic
Related