Skip to content Skip to sidebar Skip to footer

How To Pass A Variable From The Url To A View In Django?

Simple question. How can I pass a variable from the URL to the view? I'm following the Date Example. My view needs to arguments: def hours_ahead(request, offset): My url.py has t

Solution 1:

You could use Named groups in the regex

(r'^plus/(?P<offset>\d{1,2})/$', hours_ahead),

Solution 2:

I am not sure I understand your question clearly. Here is my shot at answering based on what I understood.

Adding a named regex group to your URL configuration should help:

(r'^plus/(?P<offset>\d{1,2})/$', hours_ahead),

This will let you keep the existing view:

def hours_ahead(request, offset):
    ...

Solution 3:

you can add additional variables like this:

(r'^plus/\d{1,2}/$', {'hours' : 5},  hours_ahead),

Best regards!


Solution 4:

From chapter 3 of the django book:

Now that we've designated a wildcard for the URL, we need a way of passing that wildcard data to the view function, so that we can use a single view function for any arbitrary hour offset. We do this by placing parentheses around the data in the URLpattern that we want to save. In the case of our example, we want to save whatever number was entered in the URL, so let's put parentheses around the \d{1,2}, like this:

(r'^time/plus/(\d{1,2})/$', hours_ahead),

If you're familiar with regular expressions, you'll be right at home here; we're using parentheses to capture data from the matched text.


Post a Comment for "How To Pass A Variable From The Url To A View In Django?"