Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional url parameters in class based views

How do you do create a default value for a url parameter with class based views? On for example TemplateView

For example:

url(r'^(?P<num>\d+)|/$', MyView.as_view())

if num is not specified in the url i want to set a default value of '4'

like image 436
9-bits Avatar asked Oct 30 '25 08:10

9-bits


2 Answers

If you specify a regex containing names such as:

url(r'^(?P<num>\d+)|/$', MyView.as_view())

Then num will always be passed as a keyword argument to your view function. If the regex matches but there is no num match, then num will be passed as None to your view.

Given the following view function:

def get(self, request, *args, **kwargs):
    print 'args %s' % repr(args)
    print 'kwargs %s' % repr(kwargs)

the output printed by runserver is as follows:

# url: /
args ()
kwargs {'num': None}

# url: /45/
args ()
kwargs {'num': u'45'}

It's up to you to detect a None value and assign a default as appropriate.

def get(self, request, *args, **kwargs):
    num = kwargs.get('num', None)
    if num is None:
        num = 4
like image 169
Austin Phillips Avatar answered Oct 31 '25 20:10

Austin Phillips


If num is not specified in the URL then Django won't use that line in urls.py to display a page. You can modify your URL configuration like this to make that happen:

url(r'^$', MyView.as_view())
url(r'^(?P<num>\d+)|/$', MyView.as_view())

And in MyView, you can get the parameter by doing:

def get(self, request, *args, **kwargs):
    my_url = request.GET.get('url', 4)

which either assigns the value given in the URL to my_url or 4 as a default otherwise.

like image 20
Simeon Visser Avatar answered Oct 31 '25 22:10

Simeon Visser