尝试创建一个简单的论坛。如何在Django 1.9中创建一组分层的命名URL?文档说这样做:
url(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$', views.month_archive),
我做了,作为:
url(u'^(?P<Name>.*)/(?P<ThreadName>.*)/$', views.thread, name = "thread"),
并在views.py中:
def thread(request, Name, ThreadName):
board = get_object_or_404(Board, Title = Name)
thread = get_object_or_404(Thread, Title = ThreadName)
context = { "board": board,
"thread": thread,
}
return render(request, "post/board.html", context)
但我得到一个错误,说&#34;没有董事会匹配给定的查询。&#34;,即使董事会存在,我可以在站点/名称到达它,它只在站点/名称/失败ThreadName。
答案 0 :(得分:3)
您需要使捕捉部分非贪婪。替换:
url(u'^(?P<Name>.*)/(?P<ThreadName>.*)/$', views.thread, name = "thread"),
使用:
url(u'^(?P<Name>.*?)/(?P<ThreadName>.*?)/$', views.thread, name = "thread"),
注意?
个字符 - 它们会有所不同。
或者,根据名称和线程名称的有效字符,您可以查找一个或多个 alhanumeric (\w+
)而不是任何字符:
url(r'^(?P<Name>\w+)/(?P<ThreadName>\w+)/$', views.thread, name = "thread"),