我有一个全新的Django项目.我添加了一个最小视图函数views.py
和一个URL模式urls.py
,通过函数引用而不是字符串传递视图:
# urls.py # ------- # coding=utf-8 from django.conf.urls.defaults import * from myapp import views urlpatterns = patterns('', url(r'^myview/$', views.myview), ) # views.py ---------- # coding=utf-8 from django.http import HttpResponse def myview(request): return HttpResponse('MYVIEW LOL', content_type="text/plain")
我试图reverse()
通过传递一个函数引用来获取URL.但我没有得到匹配,尽管我确认我传递给反向的视图函数与我在URL模式中放置的完全相同的视图函数:
>>> from django.core.urlresolvers import reverse >>> import urls >>> from myapp import views >>> urls.urlpatterns[0].callback is views.myview True >>> reverse(views.myview) Traceback (most recent call last): File "", line 1, in File "/Library/Python/2.5/site-packages/django/core/urlresolvers.py", line 254, in reverse *args, **kwargs))) File "/Library/Python/2.5/site-packages/django/core/urlresolvers.py", line 243, in reverse "arguments '%s' not found." % (lookup_view, args, kwargs)) NoReverseMatch: Reverse for ' ' with arguments '()' and keyword arguments '{}' not found.
据我所知,文档中的函数引用应该在URL模式和reverse()
.
带有函数引用的URL模式
reverse
带功能参考
我正在使用Django主干,修订版9092.
得到它了!!问题是一些进口是myproject.myapp.views
,而有些只是myapp.views
.这足以让Python模块系统感到困惑,以至于它不再将这些函数检测为同一个对象.这是因为你的主要settings.py
可能有一条线:
ROOT_URLCONF = `myproject.urls`
要解决此问题,请尝试在shell会话中使用完全导入:
>>> from django.core.urlresolvers import reverse >>> from myproject.myapp import views >>> reverse(views.myview) '/myview/'
这是调试会话的日志,适用于任何感兴趣的未来读者:
>>> from django.core import urlresolvers >>> from myapp import myview >>> urlresolvers.get_resolver (None).reverse_dict {None: ([(u'myview/', [])], 'myview/$'),: ([(u'myview/', [])], 'myview/$')} >>> v1 = urlresolvers.get_resolver (None).reverse_dict.items ()[1][0] >>> reverse(v1) '/myview/' >>> v1 is myview False >>> v1.__module__ 'testproject.myapp.views' >>> myview.__module__ 'myapp.views'
如果您更改URL匹配会发生r'^myview/$'
什么?
你有没有尝试过视图名称?有点像reverse ('myapp.myview')
?
是urls.py
根URLconf,还是在myapp
应用程序中?需要有从根到视图的完整路径才能解析它.如果那样myproject/myapp/urls.py
,那么myproject/urls.py
你需要这样的代码:
from django.conf.urls.defaults import patterns urlpatterns = patterns ('', (r'^/', 'myapp.urls'), )