Django 'resolve' : get the url name instead of the view_function

a 夏天 提交于 2019-12-04 16:24:08

问题


My problem is simple, I have an url, I would like to resolve it, but get the url name instead of the view function associated with it ...

For example... this is urlconf :

urlpatterns = patterns('',
...
    url('^/books/$', book_list, name="overview_books"),
...
)

And this is what I would like :

>>> resolve('/books/')
'overview_books'

Do you know any way to do this ?


回答1:


Use this snippet (originally taken from djangosnippets.org/snippets/1378/);

>>> from my_projects.tools import resolve_to_name
>>> print resolve_to_name('/some/url')
'app.views.view'
>>> print resolve_to_name('/some/other/url')
'this_is_a_named_view'

;)




回答2:


In Django 1.3 and newer you can use resolve function:

from django.core.urlresolvers import resolve
print resolve('/books/').url_name


来源:https://stackoverflow.com/questions/3165037/django-resolve-get-the-url-name-instead-of-the-view-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!