Accessing Primary Key from URL in Django View Class Accessing Primary Key from URL in Django View Class python python

Accessing Primary Key from URL in Django View Class


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


to access the primary key in viewspost =

Class_name.objects.get(pk=self.kwargs.get('pk'))


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())