django url 解析器反向查找

django url resolvers reverse lookup

NoReverseMatch

我正在尝试使用以下 urls

制作一个基本网站
/congregation/ - home page
/congregation/archives - archives for that page

有多个 'congregations',每个都有一个存档页面。

我有以下 url 模式:

church/urls.py

urlpatterns = [
url(r'^admin/', admin.site.urls, name='admin'),
url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}),
url(r'^', include('congregation.urls', namespace='congregation')),
]

church/congregation/urls.py

page_patterns = [
    url(r'^$', CongregationView.as_view(), name='home'),
    url(r'^archive/', SermonList.as_view(), name='archive')
]

urlpatterns = [
    url(r'^(?P<congregation>\w{3,20})/', include(page_patterns, namespace='page'))
]

页面按我预期的方式显示,但如果我使用 header nav-bar 中的链接,反向查找会失败并显示此消息

NoReverseMatch at /spokane/archive/
Reverse for 'archive' with arguments '()' and keyword arguments '{}'    not found. 1 pattern(s) tried: ['(?P<congregation>\w{3,20})/archive/']

错误是由模板中的无效反向匹配引起的

<li class="{% if request.resolver_match.url_name == 'archives' %}active{% endif %}">
                <a href="{% url 'congregation:page:archive' %}">Archives</a></li>

我确信这很简单,但我很难找到解决方案。 谢谢!

您的 url 模式 url(r'^(?P<congregation>\w{3,20})/', include(page_patterns, namespace='page')) 需要 congregation 关键字。当您使用 {% url 'congregation:page:archive' %} 调用 url 解析器时,您没有提供会众关键字。

Ty{% url 'congregation:page:archive' congregation=whatever %}