fir3net

PPS-Firenetbanner-780.5x190-30-03-17

Django - How can I pass a string from a URL to a view ?

Within Django the are 2 ways of using a URL parameter within a view. They are via URLConf or by using request.GET.

URLConf

With this method the URLConf file is configured to define your URL parameter via the use of regex.

Say that we have a URL that is 'www.domain.co.uk/user=value' and we want to grab 'value'.
First we would configure our urls.py with,

url(r'^user=(?P<user>\d{5})$', 'domain.views.output'),

This "value" can then be passed to a function within your view. Such as,

def output(request, user):

request.GET

The other way of achieving this is via the use of the request.GET method which is typically used when your url contains a question mark, such as 'www.domain.co.uk/?user=value'.

First of all your urls.py is configured with a standard entry.

url(r'^$', 'domain.views.output'),

We then use the request.GET to assign the "value" to the variable x.

def output(request):
   x = request.GET.get('user', '')

Tags: Django