How can I get 'pk' or 'id' in `get_context_data` from CBV?

user3284589 picture user3284589 · Feb 13, 2014 · Viewed 28.2k times · Source

How can I get 'pk' or 'id' in get_context_data from CBV DetailView?

class MyDetail(DetailView):
    model = Book
    template_name = 'book.html'
    
    def get_context_data(self, **kwargs):
            context = super(MyDetail, self).get_context_data(**kwargs)
            context['something'] = Book.objects.filter(pk=pk)
            return context

url:

url(r'^book/(?P<pk>\d+)/$', MyDetail.as_view(), name='book'),

Answer

Daniel Roseman picture Daniel Roseman · Feb 13, 2014

You can get it from self.kwargs['pk'].

I'm not sure why you want to, though, since the superclass already gets the Book corresponding to that pk - that's the whole point of a DetailView.