如何在Django视图中传递可选参数?

时间:2023-01-13 19:57:15

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

我想要这个函数,即使b没有经过它。

4 个解决方案

#1


17  

Default arguments.

默认参数。

def calculate(request, b=3):

#2


47  

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

您可能还需要更新您的URL分派,以处理可选参数(或没有)的请求。

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.

如果通过URL传递b,它会到达第一个URL定义。如果不包括可选参数,它会按下第二个定义,但会转到相同的视图,并使用您提供的默认值。

#3


5  

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

#4


-1  

def calculate(request, b=None)

#1


17  

Default arguments.

默认参数。

def calculate(request, b=3):

#2


47  

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

您可能还需要更新您的URL分派,以处理可选参数(或没有)的请求。

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.

如果通过URL传递b,它会到达第一个URL定义。如果不包括可选参数,它会按下第二个定义,但会转到相同的视图,并使用您提供的默认值。

#3


5  

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

#4


-1  

def calculate(request, b=None)