[英]Django NoReverseMatch exception with cache_page in urls.py
為什么在模板中使用url
標記時,在Django 1.4下的urls.py
中使用cache_page
函數會導致NoReverseMatch錯誤?
from django.shortcuts import render
def index(request):
'''Display the home page'''
return render(request, 'index.html')
繼cache_page
方向 :
from django.conf.urls import patterns, include, url
from django.views.decorators.cache import cache_page
from my_project.my_app import views
urlpatterns = patterns('',
url(r'^$', cache_page(60 * 60)(views.index)),
)
{% url my_project.my_app.views.index %}
NoReverseMatch at /
Reverse for 'my_project.my_app.views.index' with arguments '()' and keyword arguments '{}' not found.
錯誤消息指出的違規行當然是:
{% url my_project.my_app.views.index %}
views.py
中的cache_page
成功用作裝飾器(根據文檔不推薦) 在做反向時,Django嘗試匹配
URL
標簽 在你的代碼中, 'my_project.my_app.views.index'
是虛線路徑,然后Django將獲得實際的函數index()
並通過查找映射字典django.core.urlresolvers.get_resolver(None).reverse_dict
將其用作匹配反轉URL的鍵django.core.urlresolvers.get_resolver(None).reverse_dict
。
但是,當您纏繞view.index
通過cache_view
,在映射百科的關鍵變成了包裝。 因此查找失敗並NoReverseMatch
。 這很不方便且容易出錯,但我不確定它是否是一個bug。
然后,您可以通過使用URL
標簽來解決此問題
url(r'^$', cache_page(60 * 60)(views.index), name='my_index'),
{# in template #}
{% url my_index %}
或者像你提到的那樣在views.py
使用cache_page
作為裝飾器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.