【问题标题】:NoReverseMatch at /index/index 处的 NoReverseMatch
【发布时间】:2015-11-22 21:27:19
【问题描述】:

我试图了解为什么在尝试使用 Django Contact Form 时看到 NoReverseMatch 错误。

当我使用以下语法向 index.html 添加链接时发生错误:

<h3><a href="{% url 'contact' %}">Contact</a></h3>

如果我使用以下硬编码语法,则不会发生错误,并且 index.html 中的联系表单链接可以正常工作。

<h3><a href="contact">Contact</a></h3>

我想要实现的目标类似于 Django 教程中关于 removing hard coded urls 的内容。

我看到的完整错误是:

/index 处的 NoReverseMatch

使用参数 '()' 和关键字参数 '{}' 反转 'contact' 未找到。尝试了 0 个模式:[]

如有需要,我的urls.py缩写为:

 urlpatterns = patterns('',
    ...
    url(r'index$', views.index, name='index'),
    ...
    url(r'^contact/', include('contact_form.urls')'),
 )

我知道我遗漏了一些明显的东西!

【问题讨论】:

    标签: django django-urls


    【解决方案1】:

    这是因为没有名称为contact的url。

    url(r'^contact/', include('contact_form.urls')'),
    

    是将所有以contact 开头的url 映射到contact_form.urls 的url。官方文档没有说明如何访问contact 视图,但只要对 django 有基本了解,我们就可以这样做:

     urlpatterns = patterns('',
        ...
        url(r'index$', views.index, name='index'),
        ...
        url(r'^contact/', include('contact_form.urls', namespace='contacts')),
     )
    

    和模板中的:

    <h3><a href="{% url 'contacts:contact_form' %}">Contact</a></h3>
    

    contact_form url 名称在source code of the module 中找到。

    【讨论】:

    • 完美!如果我可以投票这个答案 X 100 我会。非常感谢,我已经研究这个问题 2 个多小时了。
    【解决方案2】:

    当你在模板中使用 {% url 'contact' %} 时,'contact' 实际上是路由的名称。在您的 url 模式中,没有使用此名称的路由。您应该在您的contact_forms.urls.py 中包含这样的内容:

    url(r'$', views.index, name='contact_index')
    

    另外,您应该将“contact/”模式更改为:

    url(r'^contact/', include('contact_form.urls', namespace='contacts'))
    

    然后在模板中创建链接时使用它:

    {% url 'contacts:contact_index' %}
    

    【讨论】:

    • 请注意,r'$' 将匹配任何 url。要只匹配一个空字符串,还需要添加一个起始锚点:r'^$'
    猜你喜欢
    • 1970-01-01
    • 2016-09-10
    • 1970-01-01
    • 2018-12-09
    • 2020-10-28
    • 2020-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多