How can I get "pk" or "id" in `get_context_data` from CVB?

How can I get 'pk' or 'id' in get_context_data from CVB 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'), 
+17
source share
6 answers

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

I'm not sure why you want, however, since the superclass already gets the book matching this pk - that's the whole point of the DetailView.

+35
source
 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=self.kwargs.get('pk')) return context 
+6
source

In get_context_data, you already have the object in self.object (and you can do self.object.pk). Here's what happens up the class hierarchy (DetailView inherits from BaseDetailView):

 class BaseDetailView(SingleObjectMixin, View): """ A base view for displaying a single object """ def get(self, request, *args, **kwargs): self.object = self.get_object() context = self.get_context_data(object=self.object) return self.render_to_response(context) 

Reading Django source code to understand things is incredibly simple.

And by the way, I'm not sure that you can always rely on the fact that kwargs has the key "pk".

+3
source

In addition to getting it from self.kwargs , as suggested by Daniel Roseman, you can use self.get_object().pk , for example, if you change your URL id from pk , say slug or something like that .

+3
source

you can just get it in the get method, for example:

 def get_context_data(self, request, pk, *args, **kwargs): context = super(MyDetail, self).get_context_data(**kwargs) context['something'] =Book.objects.filter(pk=self.kwargs.get('pk')) return context 
+1
source

self.kwargs['pk'] this does not work in Django 2.2

in detailview

self.object is an object that displays this view.

Thus, to access the fields of an object, such as id or pk , simply self.object.id or self.object.pk

So the answer in Django 2.2 could be like this:

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

Django 2.2 doc

0
source

All Articles