在模板中将字符串传递给 Django URL

Passing strings to Django URL in template

我认为这可能是一件非常简单的事情,但我终究无法弄清楚为什么这些 url 不匹配。

我的模板代码如下所示:

<form action="{% url 'view_record' "facility_report" %}" method="post">
{% csrf_token %}

{{ form }}

<input type="submit" value="View Report" name='view' label="Submit">  </form>

然后 url 应该与我的 url conf 中的这一行相匹配:

url(r'^view_record/((?P<report_type>.+)/)?$', views.view_record, name='view_record'),

我在这里错过了什么?它们根本不匹配,大多数与此相关的其他问题都来自五年前,当时引擎似乎对格式更加挑剔。

Exception Type: NoReverseMatch at /view_record/
Exception Value: Reverse for 'view_record' with arguments '('facility_report',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['view_record/((?P<report_type>(.*))/)?$']

你可以这样做:

<form action="{%url 'view_record' 'facility_report'%}" method="post">

在你的urls.py中:

url(r'^view_record/(?P<report_type>(.*))/$', views.view_record, name='view_record')

这应该将表格发送到正确的 url。

((?P<report_type>.+)/)? 中的外组是捕获组。 Django 的 url 反转无法处理嵌套的捕获组,因此它只会捕获外部组作为可能的参数。由于第一个参数不以 / 结尾,模式不匹配并抛出 NoReverseMatch

您可以将外部组更改为非捕获组,Django 将选择内部组作为捕获组。这样,参数就不必包含 /,因为只有内部组被替换,外部组按原样使用。

要创建非捕获组,请使用 ?::

启动组
url(r'^view_record/(?:(?P<report_type>.+)/)?$', views.view_record, name='view_record'),