How to access URL parameters in Django CBVs

Another common question in regards to Django is, how do I access a URL parameter captured from your URLconf(urls.py)? The and the answer is simpler than you might think. Before we get started I’m using Python 3.5.2 and Django 1.11.3. and assumes you have basic knowledge of Django Classed Based Views(CBVs) and its URL configuration.  One of the first things you should be aware if is self.kwargs  and it’s used from within your classed based view(which we will demonstrate later) so we can capture name-based keyword arguments according to your URLconf. So  first, let’s start from the beginning and look at our urls.py(URLconf) file:

urls .py

As you can see here on line 8 in my urlpatterns list, I’m using the regular expression r’group/(?P<pk>\d+)/$’ to capture the primary key of the group for later processing in the view. The parentheses allow us to capture the pattern and the ?P is a named capturing group. So the pattern this regex looks for will be /group/23/. Now, let’s take a look at retrieving that URL parameter(“pk”) in the view:

Let’s go through the steps in views.py file:

1.) On line 49 we are overriding the get_queryset method so we can used a custom crafted queryset.

2.) On line 50, we are accessing the keyword argument “pk” that was captured by our urls.py file and assigning it to the group_pk variable.

3.) On line 51, we check to see if the group exists from the captured URL keyword argument using the get_object_or_404 function.

4.) On line 52-54 we use the model.objects.filter() to find profiles that have users who are active, has an “Project Manager” account type, are a part of the same group, and then return the queryset.

And that’s it. Using self.kwargs is very beneficial when you want to do things like filter querysets based on URL parameter input, and can be used anywhere inside of Class Based View methods. Feel free to leave a comment if you have any questions, Thanks.

Further reading: Python Regular Expressions, Making Queries Django, How to use get, get_queryset, get_context_data

Leave a Reply

Your email address will not be published. Required fields are marked *