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'
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With