Django 模板中的 Django NoReverseMatch 异常

Django NoReverseMatch exception in django template

我在 django 中遇到反向问题,我在不同的 url 上尝试了与 docs 不同的方法,结果相同。例如:

url:

url(r'^(?P<year>[0-9]{4})/$', views.example, name='example'),

查看:

def example(request, year):
    data = dict()
    books_year = Book.objects.filter(publication_date__year=year)
    data['books_year'] = books_year
    return render(request, 'example.html', data)

example.html:

{% if books_year %}
    {% for book in books_year %}
        <tr>
            <td>
                {{ book.title }} |
                {% for authors in book.authors.all %}
                    {{ authors }}
                {% endfor %} |
                {{ book.publisher }} |
                {{ book.publication_date }}
            </td>
        </tr>
        <tr>
            <td>
                <a href="/2014/">2014 Archive</a>
                <a href="{% url 'example' 2014 %}">2014 Archive</a>
                 <ul> 
                    {% for yearvar in year_list %} 
                        <li><a href="{% url 'example' yearvar %}">{{ yearvar }} Archive</a></li> 
                    {% endfor %} 
                </ul>
            </td>
        </tr>
    {% endfor %}
{% endif %}

如果我用这个 <a href="/2014/">2014 Archive</a> 就可以了。 如果我用这个 <a href="{% url 'example' 2014 %}">2014 Archive</a> 尝试它,它会给我这个错误:

django.urls.exceptions.NoReverseMatch: Reverse for 'example' with arguments '(2014,)' and keyword arguments '{}' not found. 0 pattern(s) tried: []

最后,当我这样尝试时:

             <ul> 
                {% for yearvar in year_list %} 
                    <li><a href="{% url 'example' yearvar %}">{{ yearvar }} Archive</a></li> 
                {% endfor %} 
            </ul>

页面运行但未显示 link。 该页面应包含一个 link,它将重定向到 2014 年而不是其他年份。

我尝试了不同的视图、html 和 urls,当我尝试使用它们时出现了同样的错误。谁能解释一下为什么?

我的问题有 2 种可能的解决方案:

  1. 正在从我的主 urls.py 中删除 books 命名空间。

  2. 如 devxplorer 所述,在 django 模板中添加命名空间 url。

    <a href="{% url 'books:example' 2014 %}">2014 Archive</a>