30

I have one function in view like

def  calculate(request , b)

I want that this function should work even if b is not passes to it

4 Answers 4

75

You may also need to update your URL dispatch to handle the request with, or without, the optional parameter.

url(r'^calculate/?(?P<b>\d+)?/?$', 'calculate', name='calculate'),  
url(r'^calculate/$', 'calculate', name='calculate'),

If you pass b via the URL it hits the first URL definition. If you do not include the optional parameter it hits the second definition but goes to the same view and uses the default value you provided.

Sign up to request clarification or add additional context in comments.

3 Comments

Can you use both definitions in reverse('calculate', ...)?
Yes, you can provide both args and kwargs as attributes passed to the reverse method.
Super-correct ! Alternatively, since defining two separate urls is necessary, you might want to specify the default value of the missing parameter in the url itself, to keep all decisions in one place: url(r'^calculate/$', 'calculate', {'b': 3}, name='calculate'),
33

Default arguments.

def calculate(request, b=3):

Comments

13

Passing a default value to the method makes parameter optional.

In your case you can make:

def calculate(request, b=None)
    pass

Then in your template you can use condition for different behaviour:

{% if b %}
    Case A
{% else %}
    Case B
{% endif %}

Comments

0
def calculate(request, b=None)

Comments

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.