I got this error "KeyError at / ", how to fix it?

How do I fix this error, thanks for any help.

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/list/5/

Django Version: 4.1.2
Python Version: 3.10.6
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'todo_app']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback (most recent call last):
  File "/home/bieehoang/AboutMe/Python/Projects/bamboo_polls/venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
  File "/home/bieehoang/AboutMe/Python/Projects/bamboo_polls/venv/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/bieehoang/AboutMe/Python/Projects/bamboo_polls/venv/lib/python3.10/site-packages/django/views/generic/base.py", line 103, in view
    return self.dispatch(request, *args, **kwargs)
  File "/home/bieehoang/AboutMe/Python/Projects/bamboo_polls/venv/lib/python3.10/site-packages/django/views/generic/base.py", line 142, in dispatch
    return handler(request, *args, **kwargs)
  File "/home/bieehoang/AboutMe/Python/Projects/bamboo_polls/venv/lib/python3.10/site-packages/django/views/generic/list.py", line 154, in get
    self.object_list = self.get_queryset()
  File "/home/bieehoang/AboutMe/Python/Projects/bamboo_todo/todo_app/views.py", line 14, in get_queryset
    return TodoItem.objects.filter(todo_list_id=self.kwargs["id"])

Exception Type: KeyError at /list/5/
Exception Value: 'id'

/home/bieehoang/AboutMe/Python/Projects/bamboo_todo/todo_app/migrations/0001_initial.py

Generated by Django 4.1.2 on 2022-10-16 10:38


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


class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='ToDoList',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('title', models.CharField(max_length=100, unique=True)),
            ],
        ),
        migrations.CreateModel(
            name='TodoItem',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('title', models.CharField(max_length=100)),
                ('description', models.TextField(blank=True, null=True)),
                ('created_date', models.DateTimeField(auto_now_add=True)),
                ('due_date', models.DateTimeField(default=todo_app.models.one_week_hence)),
                ('todo_list', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='todo_app.todolist')),
            ],
            options={
                'ordering': ['due_date'],
            },
        ),
    ]
# /home/bieehoang/AboutMe/Python/Projects/bamboo_todo/todo_app/models.py

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

def one_week_hence():
    """
    Return 7 days after at that time create
    """
    return timezone.now() + timezone.timedelta(days=7)

class ToDoList(models.Model):
    title = models.CharField(max_length=100, unique=True)

    def get_absolute_url(self):
        """
        Return the URL for the particular data item
        """
        return reverse('list', args=[self.id])
    
    def __str__(self):
        """
        Standard Python way of creating a readable 
        repersentation of an object
        """
        return self.title

class TodoItem(models.Model):
    title = models.CharField(max_length = 100)
    description = models.TextField(null=True, blank=True)
    created_date = models.DateTimeField(auto_now_add = True)
    due_date = models.DateTimeField(default = one_week_hence)
    todo_list = models.ForeignKey(ToDoList, on_delete = models.CASCADE)
    def get_absolute_url(self):
        """"""
        return reverse(
            'item-update', args = [str(self.todo_list.id), str(self.id)]
        )
    def __str__(self):
        return f"{self.title}: due {self.due_date}"
    class Meta: 
        """
        Default ordering for ToDoItem record
        """
        ordering = ["due_date"]

/home/bieehoang/AboutMe/Python/Projects/bamboo_todo/todo_app/views.py

from django.shortcuts import render
from django.views.generic import ListView
from .models import ToDoList, TodoItem

class ListListView(ListView):
    model = ToDoList
    template_name = 'todo_app/index.html'

class ItemListView(ListView):
    model = TodoItem
    template_name = "todo_app/todo_list.html"

    def get_queryset(self):
        return TodoItem.objects.filter(todo_list_id = self.kwargs["id"])

    def get_context_data(self):
        context = super().get_context_data()
        context["todo_list"] = ToDoList.objects.get(id = self.kwargs["id"])
        return context

Then I got KeyError at /list/5/ when click to url from template to access ItemListView, can anyone tell me detail’s what I wrong and how do I fix this error? Thank everyone.

Inside class ItemListView i created 2 just to override get_query(() and get_context_data() to restrict date which I want it return. But really my logic was crash some where :sob:

Hey there.

A ListView normally dont takes any id for a specific object, since it’s goal it’s to List all, or a small set of items, not a specific item.
If you’re expecting only one item, or have a id on the url, you’re inheriting the wrong class from Django. That should be the DetailView

Thanks you for pointing, I read about docs about DetailView and used it but isn’t finished , just I’m writing a view of list things have to do in my app. So that can I use ListView and override it to get the values which I need?
And after that can you explain me why I get this KeyError please?

Please post the full traceback here.
Also do not post code/traceback images. It makes hard people to read, and makes it harder to others found a solution for a similar problem. The correct way of posting traceback/code is wrapping them around with backticks like you previously did.

**# Traceback**

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/list/5/

Django Version: 4.1.2
Python Version: 3.10.6
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'todo_app']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback (most recent call last):
  File "/home/bieehoang/AboutMe/Python/Projects/bamboo_polls/venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
  File "/home/bieehoang/AboutMe/Python/Projects/bamboo_polls/venv/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/bieehoang/AboutMe/Python/Projects/bamboo_polls/venv/lib/python3.10/site-packages/django/views/generic/base.py", line 103, in view
    return self.dispatch(request, *args, **kwargs)
  File "/home/bieehoang/AboutMe/Python/Projects/bamboo_polls/venv/lib/python3.10/site-packages/django/views/generic/base.py", line 142, in dispatch
    return handler(request, *args, **kwargs)
  File "/home/bieehoang/AboutMe/Python/Projects/bamboo_polls/venv/lib/python3.10/site-packages/django/views/generic/detail.py", line 108, in get
    self.object = self.get_object()
  File "/home/bieehoang/AboutMe/Python/Projects/bamboo_polls/venv/lib/python3.10/site-packages/django/views/generic/detail.py", line 31, in get_object
    queryset = self.get_queryset()
  File "/home/bieehoang/AboutMe/Python/Projects/bamboo_todo/todo_app/views.py", line 14, in get_queryset
    return TodoItem.objects.filter(todo_list_id = self.kwargs["list_id"])

Exception Type: KeyError at /list/5/
Exception Value: 'list_id

Ok, the error is now at your views.py

Can you post this code as well? it looks that you changed something from the last time you posted it here.

Yeah it’s my code

from django.shortcuts import render
from django.views.generic import ListView, DetailView
from .models import ToDoList, TodoItem

class ListListView(ListView):
    model = ToDoList
    template_name = 'todo_app/index.html'

class ItemListView(ListView):
    model = TodoItem
    template_name = "todo_app/todo_list.html"

    def get_queryset(self):
        return TodoItem.objects.filter(todo_list_id = self.kwargs["list_id"])
        # return TodoItem.objects.values()

    def get_context_data(self, **kwagrs):
        context = super().get_context_data()
        context["todo_list"] = ToDoList.objects.get(id = self.kwargs["list_id"])
        return context

Again, if this is a ListView you won’t have a id on the self.kwargs.
So this code

And this code

Will not work.

You said that wants to filter by some date, but on your views you’re trying to filter by a ID.

Do you still want to filter by ID or you want to filter by some date?

1 Like

my fail, I mean to filter data by id. Can you teach me more how to solve it?

That’s when the documentation kicks in.
What are you trying to do is a DetailView, it’s covered on the docs here and here.
If you only to want filter by a specific id, you don’t need to override the get_queryset / get_context_data. The detail view will do that based on your url configuration.
And on your template you can access the object using object.

1 Like

Thank you so much, your explaination is so clear with me, a django-newer. Wish you all good things.

1 Like

[SOLVED]
With strong help from leandrodesouzadev, I realized actually I created a fool fail below

/home/bieehoang/AboutMe/Python/Projects/bamboo_todo/todo_app/models.py
def get_queryset(self):
        return TodoItem.objects.filter(todo_list_id = self.kwargs["list_id"]) # key
def get_context_data(self):
        context = super().get_context_data()
        context["todo_list"] = ToDoList.objects.get(id = self.kwargs["list_id"]) # also same here
        return context

And then, problem actually is at my urls.py I was set the path is:

# /home/bieehoang/AboutMe/Python/Projects/bamboo_todo/todo_app/urls.py
from django.urls import path, include
from . import views
app_name = 'todo'
urlpatterns = [
    path('', views.ListListView.as_view(), name = 'index'), 
    path('list/<int:pk>/', views.ItemListView.as_view(), name = 'items')
]
"""
Error from right here, I get url like this, then 
when access this url, the views.py will be excuted 
and get the key I was created up on. But it doesn't exist, 
so forth a little bit error was appeared.  
"""

So to solve it, i just have to change:

# /home/bieehoang/AboutMe/Python/Projects/bamboo_todo/todo_app/models.py
return TodoItem.objects.filter(todo_list_id = self.kwargs["int:pk"]) # same with the key which I created at urls.py

or:

# /home/bieehoang/AboutMe/Python/Projects/bamboo_todo/todo_app/urls.py
 path('list/<int: list_id>/', views.ItemListView.as_view(), name = 'items') # same with the key in function which I want to restrict data at models.py