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'

1
  • Could you post some code to show what you're trying to do? Commented Jan 20, 2013 at 21:33

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

2

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.

3 Comments

I would strongly suggest to avoid overriding 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.
@BerislavLopac Agreed. That is one thing that makes CBV's a little awkward though -- you need to know which method to override. There is more than one way to do things, and it is not clear without proper experience which method to override.
I'm going to leave these two resources for Django and Django Rest that is absolutely necessary when working with django. Its the documentation on CBV of each class and each function that can be easily copied to properly override functions ccbv.co.uk cdrf.co

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.