Python 如何在 django 中通过 url 传递参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32567808/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:49:29  来源:igfitidea点击:

How do I pass parameters via url in django?

pythondjango

提问by Sa?a Kalaba

I am trying to pass a parameter to my view, but I keep getting this error:

我正在尝试将参数传递给我的视图,但我不断收到此错误:

NoReverseMatch at /pay/how

Reverse for 'pay_summary' with arguments '(False,)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['pay/summary/$']

/pay/howis the current view that I'm at. (that is the current template that that view is returning).

/pay/how是我目前的观点。(即该视图返回的当前模板)。

urls.py

网址.py

url(r'^pay/summary/$', views.pay_summary, name='pay_summary')

views.py

视图.py

def pay_summary(req, option):
    if option:
        #do something
    else:
        #do something else
    ....

template

模板

<a href="{% url 'pay_summary' False %}">my link</a>

EDIT

编辑

I want the view should accept a POST request, not GET.

我希望视图应该接受 POST 请求,而不是 GET。

采纳答案by Dric512

You need to define a variable on the url. For example:

您需要在 url 上定义一个变量。例如:

url(r'^pay/summary/(?P<value>\d+)/$', views.pay_summary, name='pay_summary')),

In this case you would be able to call pay/summary/0

在这种情况下,您可以调用 pay/summary/0

It could be a string true/false by replacing \d+to \s+, but you would need to interpret the string, which is not the best.

通过替换\d+to \s+,它可能是一个字符串真/假,但您需要解释该字符串,这不是最好的。

You can then use:

然后您可以使用:

<a href="{% url 'pay_summary' value=0 %}">my link</a>

回答by Rexcirus

To add to the accepted answer, in Django 2.0 the url syntax has changed:

要添加到已接受的答案中,在 Django 2.0 中,url 语法已更改:

path('<int:key_id>/', views.myview, name='myname')

Or with regular expressions:

或者使用正则表达式:

re_path(r'^(?P<key_id>[0-9])/$', views.myview, name='myname')