django - 未找到关键字参数 '' 的反向 ''

标签 django python-3.x url

我正在使用 django 2.1python 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/

相关文章:

python - Django URL 中的 Slug

django - 注册的模型不显示在管理员中

iPhone - UIWebview - 获取单击链接的 URL

python-3.x - Python (c) 配置文件 : Error importing SortKey from pstats

apache - pom.xml中项目标签下的 "<url>http://maven.apache.org</url>"标签是什么?

rest - 将特殊字符作为 URI 参数的一部分传递

python - 将值从一个类/函数传递到另一个类/函数

python - 查询集对象不可调用 Django

python-3.x - pandas 列出相同的索引

python - 如何根据 Pandas 中的依赖值更新数据框?