问题描述
我正在研究 Django 文档,但遇到了一个我无法理解的部分:在实际问题中如何使用命名空间的真实示例是什么.我知道语法,但我不知道这样做的目的.
I am studying the Django documentation, but I encountered a part that I cannot understand: what is a real example of how use to use a namespace in a real problem. I know the syntax but I do not know the purpose of this.
推荐答案
通常,它们用于将每个应用程序的 URL 放入它们自己的命名空间中.这可以防止 reverse()
Django 函数和 {% url %}
模板函数返回错误的 URL,因为 URL 模式名称碰巧在另一个应用程序中匹配.
Typically, they are used to put each application's URLs into their own namespace. This prevents the reverse()
Django function and the {% url %}
template function from returning the wrong URL because the URL-pattern name happened to match in another app.
我在项目级 urls.py
文件中的内容如下:
What I have in my project-level urls.py
file is the following:
from django.conf.urls.defaults import *
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', 'main.views.main', name='main'),
url(r'^login$', 'django.contrib.auth.views.login', name="login"),
url(r'^logout$', 'django.contrib.auth.views.logout',
{"next_page": "/"}, name="logout"),
# Admin
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
)
# Auto-add the applications.
for app in settings.LOCAL_APPS:
urlpatterns += patterns('',
url(r'^{0}/'.format(app), include(app + '.urls', namespace=app)),
)
注意最后一部分:这通过我安装的应用程序(settings.LOCAL_APPS
是我添加的一个设置,只包含我的应用程序;它被添加到 INSTALLED_APPS
它有其他东西,如 South),在每个文件中查找 urls.py
,并将这些 URL 导入到以应用命名的命名空间中,并将这些 URL 放入以应用命名的 URL 子目录中应用程序.
Note the last section: this goes through the applications I have installed (settings.LOCAL_APPS
is a setting I added that contains only my apps; it gets added to INSTALLED_APPS
which has other things like South), looks for a urls.py
in each of them, and imports those URLs into a namespace named after the app, and also puts those URLs into a URL subdirectory named after the app.
例如,如果我有一个名为 hosts
的应用程序,并且 hosts/urls.py
看起来像:
So, for example, if I have an app named hosts
, and hosts/urls.py
looks like:
from django.conf.urls.defaults import *
urlpatterns = patterns('hosts.views',
url(r'^$', 'show_hosts', name='list'),
)
现在我的 views.py
可以调用 reverse("hosts:list")
来获取调用 hosts.views.show_hosts,它看起来像
"/hosts/"
.模板中的 {% url "hosts:list" %}
也是如此.这样我就不必担心与另一个应用程序中名为list"的 URL 发生冲突,而且我不必在每个名称前加上 hosts_
.
Now my views.py
can call reverse("hosts:list")
to get the URL to the page that calls hosts.views.show_hosts
, and it will look something like "/hosts/"
. Same goes for {% url "hosts:list" %}
in a template. This way I don't have to worry about colliding with a URL named "list" in another app, and I don't have to prefix every name with hosts_
.
请注意,登录页面位于 {% url "login" %}
因为它没有命名空间.
Note that the login page is at {% url "login" %}
since it wasn't given a namespace.
这篇关于URL命名空间的真实例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!