[Django]-How can i pass optional arguments in Django view

32👍

Default arguments.

def calculate(request, b=3):

74👍

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.

👤vjimw

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 %}
👤Kee

0👍

def calculate(request, b=None)

Leave a comment