How can i pass optional arguments in Django view

29,177

Solution 1

Default arguments.

def calculate(request, b=3):

Solution 2

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.

Solution 3

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 %}
Share:
29,177

Related videos on Youtube

tej.tan
Author by

tej.tan

Updated on July 09, 2022

Comments

  • tej.tan
    tej.tan almost 2 years

    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

  • Tomas Tomecek
    Tomas Tomecek over 11 years
    I think that this is the most important part of the answer.
  • naktinis
    naktinis over 10 years
    Can you use both definitions in reverse('calculate', ...)?
  • vjimw
    vjimw over 10 years
    Yes, you can provide both args and kwargs as attributes passed to the reverse method.
  • Mario Orlandi
    Mario Orlandi over 5 years
    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'),