Luke Luke - 7 months ago 50
Python Question

Accessing Primary Key from URL in Django View Class

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?


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