Django – Capture Arguments in URL Patterns and Pass Them to View Functions


As you already know when a request comes to your Django site, it first looks for the url patterns of your site and once a patter is matched related view function is called passing some arguments to that function.

But how do you catch those arguments? How do you know which arguments you are sending to your view functions?

First things first. To capture a parameter in a regex url pattern in your file, you surround the part of your regex you want to match and capture with parenthesis.

Let’s say you have the line below in your file:

And let’s say you have the below view function in your file (details of the function is not important right now):

Here “request” is Http Request that goes for every view function. What we do here is we surround (.*) part of the regex and capture its value in the url for the incoming request (if we have a match). Then this captured value is provided to “category_view” function as the value for “my_category_name” parameter.

Keyword Arguments and Positional Arguments

A Python function can be called using keyword arguments, named arguments and sometimes both, and so there are 2 ways to capture and pass parameters in url patterns to view functions.

Capturing and Passing by Position

This way you specify no name for the values you are capturing. Captured values are passed to view function by the order they are captured.

Here /articles/2006/03/ request would result in this function call: view_archive(request, ‘2006’, ’03’).

Capturing and Passing by Name

Here you specify a name for each parameter you capture. You specify the parameter name using ?P<param_name>.

Here/articles/2006/03/ request would result in this function call: view_archive(request, year=’2006′, month=’03’).

Hope this helps.
Good Luck,