我有以下urlpatterns
:
urlpatterns = patterns('',
url(r'^new$', 'webapp.views.new_post', name="new_post"),
url(r'^$', 'webapp.views.all_posts', name="main"),
url(r'^post/(\d{4})/(\d{2})/(\d{2})/$', 'webapp.views.single_post', name="single_post"),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
)
一个看起来像这样的模板:
{% for i in posts %}
<h3><a href={% url 'single_post' i.created_at.year i.created_at.month i.created_at.day %}>{{i.title}}</a></h3>
Posted at: {{i.created_at}}
<br>
<br>
{{i.text}}
<hr>
{% endfor %}
但我不断收到NoReverseMatch
Reverse for 'single_post' with arguments '(2012, 9, 30)' and keyword arguments '{}' not found.
例外情况
编辑:我在Python 2.7上使用Django 1.4.1
答案 0 :(得分:3)
对于single_post的url def需要3个args,但是你传递了4个
所以而不是
<h3><a href={% url 'single_post' i.created_at.year i.created_at.month i.created_at.day i.slug %}>{{i.title}}</a></h3>
你想要的可能
<h3><a href={% url 'single_post' i.created_at.year i.created_at.month i.created_at.day %}>{{i.title}}</a></h3>
哦,但是你可能想要最后的slug,在你的urls.py中,将它改为像...
url(r'^post/(\d{4})/(\d{2})/(\d{2})/([\w-]+)$', 'webapp.views.single_post', name="single_post")
答案 1 :(得分:1)
来自python docs:
{m}指定应匹配前一个RE的m个副本;较少的匹配导致整个RE不匹配。例如,{6}将恰好匹配六个'a'字符,但不匹配五个。
所以url模式应该是:
r'^post/(\d{4})/(\d{1,2})/(\d{1,2})/$'
希望这有帮助。