我收到一个错误,说:
NoReverseMatch at /books/
Reverse for 'urlvar' not found. 'urlvar' is not a valid
view function or pattern name.
我想{% with %}
标签在 books/index.html 中效果不佳 但我不知道如何解决这个问题。
这是我的代码:
书籍/网址.py
from django.conf.urls import url
from books import views
urlpatterns = [
url(r'^$', views.BooksModelView.as_view(), name='index'),
url(r'^book/$', views.BookList.as_view(), name='book_list'),
url(r'^author/$', views.AuthorList.as_view(), name='author_list'),
url(r'^publisher/$', views.PublisherList.as_view(), name='publisher_list'),
url(r'^book/(?P<pk>d+)/$', views.BookDetail.as_view(), name='book_detail'),
url(r'^author/(?P<pk>d+)/$', views.AuthorDetail.as_view(), name='author_detail'),
url(r'^publisher/(?P<pk>d+)/$', views.PublisherDetail.as_view(), name='publisher_detail'),
]
templates/books/index.html
{% extends 'base_books.html' %}
{% block content %}
<h2>Books Management Systemt</h2>
<ul>
{% for modelname in object_list %}
{% with 'books:'|add:modelname|lower|add:'_list' as urlvar %}
<li><a href="{% url 'urlvar' %}">{{ modelname }}</a></li>
{% endwith %}
{% endfor %}
</ul>
{% endblock %}
urlvar
是一个变量,因此您在{% url %}
标记中使用urlvar
而不是字符串'urlvar'
。
<li><a href="{% url urlvar %}">{{ modelname }}</a></li>
如果您愿意,可以在标记中构造 URL 模式名称,或者如果您发现with
标记更具可读性,则可以保留该标记。
<li><a href="{% url 'books:'|add:modelname|lower|add:'_list' %}">{{ modelname }}</a></li>
由于在反转 url 时使用'books:
命名空间,因此应在books/urls.py
文件中设置app_name
。
from django.conf.urls import url
from books import views
app_name = 'books'
urlpatterns = [
...
]