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'
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.
get unless it's absolutely necessary. Class-based views offer a bunch of methods which are more appropriate for this, depending on the actual View class you're subclassing and what do you intend to do with this parameter. For example, if you need it to instantiate the object in DetailView, override get_object; if you just want to use it in the template, use get_context_data; and so on.