我正在使用 django 2.1
和 python 3.6
并且我遇到了一个看起来像 other people 的问题过去几年遇到过。
这是我的views.py
的一部分:
def blog_list_by_cat(request, cat_id, cat_name):
...
def blog_list_by_genre(request, genre_id, genre_name):
...
这是我的urls.py
:
urlpatterns = [
path('', views.index, name='index'),
re_path(r'^blog/(?P<blog_id>\d+)/(?P<slug>[^/]+)/?$', views.single_blog, name='single_blog'),
re_path(r'^blog-list/(?P<cat_id>\d+)/(?P<cat_name>[^/]+)/?$', views.blog_list_by_cat, name='blog_list_by_cat'),
path('blog-list/latest/', views.blog_latest, name='blog_latest'),
re_path(r'^blog-list/genre/(?P<genre_id>\d+)/(?P<genre_name>[^/]+)/?$', views.blog_list_by_genre, name='blog_list_by_genre'),
]
在我的模板中,当我调用这些链接时,这个效果很好:
{% for cat in cat_list %}
<a class="dropdown-item" href="{% url 'blog_list_by_cat' cat_id=cat.id cat_name=cat.cat %}">{{ cat.cat }}</a>
{% endfor %}
虽然这个在同一模板中抛出错误:
{% for genre in genre_list %}
<li><a class="dropdown-item" href="{% url 'blog_list_by_genre' genre_id=genre.id genre_name=genre.title %}">{{ genre.title }}</a></li>
{% endfor %}
这是完整的错误:
Exception Type: NoReverseMatch
Exception Value: Reverse for 'blog_list_by_genre' with keyword arguments '{'genre_id': 5, 'genre_name': 'Action'}' not found. 1 pattern(s) tried: ['blog-list/genre/(?P\d+)/(?P[^/]+)/?$']
如您所见,我正在使用 named urls我在 url 名称周围使用引号,而不是在 url 中添加应用程序名称。两个代码是相同的。但为什么第二个不起作用呢?
最佳答案
尝试使用非贪婪限定符:
(?P<genre_name>.+?)
有时,当我的模型名称中包含空格(例如“太空针塔”)时,这可以帮助我匹配网址。
关于django - 未找到关键字参数 '' 的反向 '',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53368943/