如何使用django.core.urlresolvers.reverse与函数引用而不是命名的URL模式? [英] How do I use django.core.urlresolvers.reverse with a function reference instead of a named URL pattern?

查看:357
本文介绍了如何使用django.core.urlresolvers.reverse与函数引用而不是命名的URL模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 urls.py 文件中,我有:

 从myapp导入视图
...
(r'^ categories / $',views.categories)

其中类别 myapp / views.py 中的视图函数。没有其他的URLconf行引用 views.categories



在单元测试文件中,我试图抓住这个使用 django.core.urlresolvers.reverse()的URL,而不是只复制'/ categories /'(DRY和所有这些)。所以,我有:

  from django.core.urlresolvers import reverse 
from myapp import views


url = reverse(views.categories)

当我运行我的测试,我得到一个 NoReverseMatch 错误:

  NoReverseMatch: '< 0x1082f30>的函数类别,带有参数'()'和关键字参数'{}'未找到。 

如果我将URL模式命名为模式,它匹配得很好,如下所示:

  url(r'^ categories / $',views.categories,'myapp-categories')

并使用模式名称来匹配:

  url = reverse('myapp-categories')

但是据我所知, a href =http://docs.djangoproject.com/en/dev/topics/http/urls/#reverse =noreferrer> reverse documentation ,我不应该使它成为一个命名的URL模式,只是为了使用 reverse



任何想法我在做错什么?

解决方案

经过进一步的调查,结果是我是如何导入意见的问题模块:



如何成功通过a函数参考Django的reverse()函数?



感谢您的帮助,但是,你们启发我正确地看着它。 b $ b

In my urls.py file, I have:

from myapp import views
...
(r'^categories/$', views.categories)

Where categories is a view function inside myapp/views.py. No other URLconf lines reference views.categories.

In a unit test file, I’m trying to grab this URL using django.core.urlresolvers.reverse(), instead of just copying '/categories/' (DRY and all that). So, I have:

from django.core.urlresolvers import reverse
from myapp import views
...

url = reverse(views.categories)

When I run my tests, I get a NoReverseMatch error:

NoReverseMatch: Reverse for '<function categories at 0x1082f30>' with arguments '()' and keyword arguments '{}' not found.

It matches just fine if I make the URL pattern a named pattern, like this:

url(r'^categories/$', views.categories, 'myapp-categories')

And use the pattern name to match it:

url = reverse('myapp-categories')

But as far as I can tell from the reverse documentation, I shouldn’t need to make it a named URL pattern just to use reverse.

Any ideas what I’m doing wrong?

解决方案

After futher investigation, turns out it was an issue with how I was importing the views module:

How do I successfully pass a function reference to Django’s reverse() function?

Thanks for the help though, guys: you inspired me to look at it properly.

这篇关于如何使用django.core.urlresolvers.reverse与函数引用而不是命名的URL模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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