Getting pk from DetailView for lte/gte comparison (Django)

Viewed 86

Goal: Implement next article / previous article feature on article page which is being served via DetailView. Compare current article pk against queryset in order to grab the next and previous articles.

I've tried a lot of different methods so far, but I'm getting errors on all of them.

class PostDetail(generic.DetailView):
    model = Post
    template_name = 'post_detail.html'

    def get_context_data(self, **kwargs):
        context = super(PostDetail, self).get_context_data(**kwargs)
        pk = Post.objects.filter(pk=self.kwargs.get('pk'))

I've also tried:

pk = self.kwargs.get('pk')

and

pk = self.kwargs['pk']

I get KeyError on the dictionary attempt and None on the get attempts.

I can't figure out why I'm not able to return the pk for the article in order to finish the code. Also, I've tried to get other data from the Post model, with the same errors.

edit:

URL's:

urlpatterns = [
    path('', views.home, name='home'),
    path('cars/<slug:slug>', views.categories, name='categories_detail'),
    path('<slug:categories_detail>/<slug:slug>', views.PostDetail.as_view(), name='post_detail'),
]
1 Answers

It can be seen from your url pattern that you are using the slug to get the correct Post object, and you never pass pk to the view. Instead you can get the pk from the object itself:

class PostDetail(generic.DetailView):
    model = Post
    template_name = 'post_detail.html'

    def get_context_data(self, **kwargs):
        context = super(PostDetail, self).get_context_data(**kwargs)
        pk = self.object.pk
        # Your code
        return context
Related