33

I have a URL pattern mapped to a custom view class in my Django App, like so:

url( r'^run/(?P<pk>\d+)/$', views.PerfRunView.as_view( ))

The problem is, I cannot figure out how I can access 'pk' from the URL pattern string in my view class so that I can retrieve a specific model object based on its database id. I have googled, looked through the Django documentation, searched Stack Overflow, and I can't find a satisfactory answer at all.

Can anybody tell me?

Luke
  • 2,434
  • 9
  • 39
  • 64
  • 1
    http://stackoverflow.com/questions/6427004/django-generic-view-subclassed-url-parameters does this help ? – Ankur Gupta Nov 23 '12 at 11:29
  • 1
    https://docs.djangoproject.com/en/1.4/topics/class-based-views/#performing-extra-work read the second note. – iMom0 Nov 23 '12 at 11:31
  • @Ankur Gupta Thanks for the links, but I'm still not totally clear on it. Is it part of self.kwargs? I thought I was getting the hang of Django, until I got into class-based views. I just don't understand them at all. – Luke Nov 23 '12 at 11:50
  • 1
    @luke class based view is just an abstraction I for one finds it annoying and stick to functions. I don't think they help a lot. Not necessary you need to use it. Using simple function against URLs work fine too. – Ankur Gupta Nov 24 '12 at 07:52

4 Answers4

77

In a class-based view, all of the elements from the URL are placed into self.args (if they're non-named groups) or self.kwargs (for named groups). So, for your view, you can use self.kwargs['pk'].

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • 1
    I've sorted it now. I even have a better understanding of how Django View classes work, too. Thanks! – Luke Nov 23 '12 at 12:11
15

to access the primary key in views post =

Class_name.objects.get(pk=self.kwargs.get('pk'))
Rich Benner
  • 7,873
  • 9
  • 33
  • 39
raghu
  • 384
  • 7
  • 10
1

This is an example based on django restframework to retrieve an object using pk in url:

views.py

class ContactListView(generics.ListAPIView):
    queryset = Profile.objects.all()
    serializer_class = UserContactListSerializer

    def get(self, request, pk, *args, **kwargs):
        contacts = Profile.objects.get(pk=pk)
        serializer = UserContactListSerializer(contacts)
        return Response(serializer.data)

urls.py

    url(r'^contact_list/(?P<pk>\d+)/$', ContactListView.as_view())
Milad shiri
  • 812
  • 7
  • 5
0

As many have said self.kwargs works fine. It particularly helps in self.get_queryset() function, unlike list, create where pk works better.