Reputation: 2486
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?
Upvotes: 34
Views: 54073
Reputation: 11
As many have said self.kwargs
works fine.
It particularly helps in self.get_queryset()
function, unlike list
, create
where pk
works better.
Upvotes: 0
Reputation: 990
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())
Upvotes: 1
Reputation: 394
to access the primary key in views post =
Class_name.objects.get(pk=self.kwargs.get('pk'))
Upvotes: 15
Reputation: 599628
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']
.
Upvotes: 77