如何成功将函数引用传递给Django的reverse()函数?

时间:2008-09-28 19:15:15

标签: python django

我有一个全新的Django项目。我向views.py添加了一个最小视图函数,向urls.py添加了一个URL模式,通过函数引用而不是字符串传递视图:

# 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 "<console>", line 1, in <module>
  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 '<function myview at 0x6fe6b0>' with arguments '()' and keyword arguments '{}' not found.

据我在文档中可以看出,函数引用在URL模式和reverse()都应该没问题。

我正在使用Django主干,修订版9092.

2 个答案:

答案 0 :(得分:10)

得到了!!问题是某些导入是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/$'), <function myview at 0x845d17c>: ([(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'

如果您将网址匹配更改为r'^myview/$'会怎样?


您是否尝试过使用视图名称?像reverse ('myapp.myview')

这样的东西

{URL}是urls.py,还是myapp应用程序?需要有从根到视图的完整路径才能解析它。如果那是myproject/myapp/urls.py,那么在myproject/urls.py中你需要这样的代码:

from django.conf.urls.defaults import patterns
urlpatterns = patterns ('',
    (r'^/', 'myapp.urls'),
)

答案 1 :(得分:1)

如果你的两个代码粘贴完整,那么它看起来不像第二个,这使得实际调用reverse(),导入urls模块,因此如果实际实现了url映射。