Luke Luke - 1 year ago 100
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?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download