NoReverseMatch when using {% url %} in Django
I am following a book (Practical Django Projects 2nd Ed.), and I have run across an error that I cannot figure out.
I get this error: TemplateSyntaxError at /weblog/
Caught NoReverseMatch while rendering: Reverse for 'coltrane_category_list' with arguments '()' and keyword arguments '{}' not found.
Here is the code in my template that uses {% url %}:
<li id="main-nav-entries">
<a hr开发者_运维知识库ef="{% url coltrane_entry_archive_index %}">Entries</a>
</li>
Here is my URL configuration:
entry_info_dict = {
'queryset': Entry.objects.all(),
'date_field': 'pub_date',
}
urlpatterns = patterns('django.views.generic.date_based',
(r'^$', 'archive_index', entry_info_dict, 'coltrane_entry_archive_index'),
(r'^(?P<year>\d{4})/$', 'archive_year', entry_info_dict, 'coltrane_entry_archive_year'),
(r'^(?P<year>\d{4})/(?P<month>\w{3})/$', 'archive_month', entry_info_dict, 'coltrane_entry_archive_month'),
(r'^(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{2})/$', 'archive_day', entry_info_dict, 'coltrane_entry_archive_day'),
(r'^(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{2})/(?P<slug>[-\w]+)/$', 'object_detail', entry_info_dict, 'coltrane_entry_detail'),
)
What does the error mean? Am I not giving it enough arguments? How does the {% url %} work? From my understanding, it will look at the URL configuration and find the matching keywords and give back a URL based on the matching keyword in the URL configuration.
You have to use the url
function on your patten for it to register that pattern's name properly. See the Django documentation on naming url patterns.
Basically, change your patterns to:
urlpatterns = patterns('django.views.generic.date_based',
url(r'^$', 'archive_index', entry_info_dict, name='coltrane_entry_archive_index'),
url(r'^(?P<year>\d{4})/$', 'archive_year', entry_info_dict, name='coltrane_entry_archive_year'),
url(r'^(?P<year>\d{4})/(?P<month>\w{3})/$', 'archive_month', entry_info_dict, name='coltrane_entry_archive_month'),
url(r'^(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{2})/$', 'archive_day', entry_info_dict, name='coltrane_entry_archive_day'),
url(r'^(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{2})/(?P<slug>[-\w]+)/$', 'object_detail', entry_info_dict, name='coltrane_entry_detail'),
)
I think it works without using name=
as a named arg but I always prefer to because it's more explicit to me.
精彩评论