How can i pass optional arguments in Django view
29,177
Solution 1
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 %}
Related videos on Youtube
Author by
tej.tan
Updated on July 09, 2022Comments
-
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 over 11 yearsI think that this is the most important part of the answer.
-
naktinis over 10 yearsCan you use both definitions in
reverse('calculate', ...)
? -
vjimw over 10 yearsYes, you can provide both args and kwargs as attributes passed to the reverse method.
-
Mario Orlandi over 5 yearsSuper-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'),