Search code examples
pythondjangodjango-viewsdjango-querysetdjango-urls

KeyError at /x/x/ 'pk' django


I'm trying to get a DetailView's model's pk in a variable in the get_context_data but I keep getting the error KeyError at /x/x/ 'pk'.

views.py

class MangaView(DetailView):
    model = Manga
    template_name = 'mangas/manga.html'
    context_object_name = 'manga'
    slug_field = 'manga_slug'
    slug_url_kwarg = 'manga_slug'

    def get_context_data(self, **kwargs):
        data = super().get_context_data(**kwargs)

        manga = get_object_or_404(Manga, id=self.kwargs['pk'])  # error line
        favorited = False
        latered = False
        ...
        return data

urls.py

urlpatterns = [
    path('mangas/', MangasHomeView.as_view(), name='mangas-home'),
    path('manga/<slug:manga_slug>/', MangaView.as_view(), name='manga'),
    ...
]

Solution

  • The error you are seeing is caused by trying to access the pk value through self.kwargs, when in fact your view is using a slug field and slug URL parameter.

    Try to use self.get_object() as it gives you current instance in DetailView whether it is pk or slug so:

    class MangaView(DetailView):
        model = Manga
        template_name = 'mangas/manga.html'
        context_object_name = 'manga'
        slug_field = 'manga_slug'
        slug_url_kwarg = 'manga_slug'
    
        def get_context_data(self, **kwargs):
            data = super().get_context_data(**kwargs)
    
            manga = self.get_object()
            favorited = False
            latered = False
            ...
            return data