Accessing Primary Key from URL in Django View Class
Asked Answered
S

4

34

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?

Seafarer answered 23/11, 2012 at 11:7 Comment(4)
#6427504 does this help ?Yardmaster
docs.djangoproject.com/en/1.4/topics/class-based-views/… read the second note.Elevenses
@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.Seafarer
@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.Yardmaster
L
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'].

Legibility answered 23/11, 2012 at 12:0 Comment(1)
I've sorted it now. I even have a better understanding of how Django View classes work, too. Thanks!Seafarer
O
15

to access the primary key in views post =

Class_name.objects.get(pk=self.kwargs.get('pk'))
Orrin answered 24/6, 2016 at 10:34 Comment(0)
O
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())
Odds answered 23/5, 2018 at 5:14 Comment(0)
F
0

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

Flout answered 1/4, 2023 at 14:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.