如何成功地将函数引用传递给Django的reverse()函数? [英] How do I successfully pass a function reference to Django’s reverse() function?

查看:80
本文介绍了如何成功地将函数引用传递给Django的reverse()函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 #urls.py 
#-------

#编码= utf-8

from django.conf.urls.defaults import *

from myapp import views


urlpatterns = patterns('',
url(r'^ myview / $',views.myview),



# .py
----------

#编码= utf-8

从django.http导入HttpResponse


def myview(request):
return HttpResponse('MYVIEW LOL',content_type =text / plain)

我试图使用 reverse()来获取URL,传递一个函数引用。但是我没有得到一个匹配,尽管确认我的传递反向的视图功能是完全相同的视图功能我放在URL模式:

 >>>来自django.core.urlresolvers import reverse 
>>>>导入网址
>>>从myapp导入视图

>>> urls.urlpatterns [0] .callback是views.myview
True

>>> reverse(views.myview)
追溯(最近的最后一次调用):
文件< console>,第1行,< module>
文件/Library/Python/2.5/site-packages/django/core/urlresolvers.py,第254行,反向
* args,** kwargs))
文件 /Library/Python/2.5/site-packages/django/core/urlresolvers.py,第243行,反向
arguments'%s'not found。 %(lookup_view,args,kwargs))
NoReverseMatch:对于'< function myview at 0x6fe6b0>'与参数'()'和关键字参数'{}'未找到相反。

从文档可以看出,函数引用在URL模式和 reverse()





我正在使用Django中继,修订版9092。

解决方案

得到了!问题是某些导入是 myproject.myapp.views ,有些仅是 myapp.views 。这使Python模块系统感到困惑,因为它不再将功能检测为同一个对象。这是因为您的主要 settings.py 可能有一行如下:

  ROOT_URLCONF =`myproject.urls` 

要解决这个问题,请尝试在shell会话中使用完整导入:

 >>>来自django.core.urlresolvers import reverse 
>>>>来自myproject.myapp import views
>>> reverse(views.myview)
'/ myview /'

这是一个调试日志会话,对于任何有兴趣的未来读者:

 >>>来自django.core import urlresolvers 
>>>>从myapp import myview
>>> urlresolvers.get_resolver(无).reverse_dict
{无:([(u'myview /',[])],'myview / $'),< function myview at 0x845d17c> ;:([(u'myview /',[])],'myview / $')}
>>> v1 = urlresolvers.get_resolver(None).reverse_dict.items()[1] [0]
>>> reverse(v1)
'/ myview /'
>>> v1是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'),


I’ve got a brand new Django project. I’ve added one minimal view function to views.py, and one URL pattern to urls.py, passing the view by function reference instead of a string:

# 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")

I’m trying to use reverse() to get the URL, by passing it a function reference. But I’m not getting a match, despite confirming that the view function I’m passing to reverse is the exact same view function I put in the URL pattern:

>>> 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.

As far as I can tell from the documentation, function references should be fine in both the URL pattern and reverse().

I’m using the Django trunk, revision 9092.

解决方案

Got it!! The problem is that some of the imports are of myproject.myapp.views, and some are just of myapp.views. This is confusing the Python module system enough that it no longer detects the functions as the same object. This is because your main settings.py probably has a line like:

ROOT_URLCONF = `myproject.urls`

To solve this, try using the full import in your shell session:

>>> from django.core.urlresolvers import reverse
>>> from myproject.myapp import views
>>> reverse(views.myview)
'/myview/'

Here's a log of the debugging session, for any interested future readers:

>>> 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'

What happens if you change the URL match to be r'^myview/$'?


Have you tried it with the view name? Something like reverse ('myapp.myview')?

Is urls.py the root URLconf, or in the myapp application? There needs to be a full path from the root to a view for it to be resolved. If that's myproject/myapp/urls.py, then in myproject/urls.py you'll need code like this:

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

这篇关于如何成功地将函数引用传递给Django的reverse()函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆