Accessing Primary Key from URL in Django View Class

Question:

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?

Asked By: Luke

||

Answers:

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'].

Answered By: Daniel Roseman

to access the primary key in views
post =

Class_name.objects.get(pk=self.kwargs.get('pk'))
Answered By: raghu

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())
Answered By: Milad shiri

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

Answered By: Prashant Goyal
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.