在站点 url.py 中指定 Django URL-命名空间的原因是什么?

What is the reason for specifying Django URL-Namespaces in the sites url.py?

我从 Django 开始,令我困惑的是 URL-命名空间的规范。据我了解,您在站点项目 urls.py 中指定它们,如下所示:

urlpatterns = patterns('',
    url(r'^polls/', include('polls.urls', namespace="polls")),
    url(r'^admin/', include(admin.site.urls)),
)

之后,命名空间可以在投票应用程序的模板中使用。

我担心的是:为什么应用程序中没有指定名称空间,可以重复使用并在另一个站点中获取另一个名称空间,因此模板不再起作用。我正在考虑 java 中的包或 C++ 中的名称空间,它们是在库中定义的,而不是在使用的应用程序中定义的。

谁能给我解释一下,为什么要这样设计?

谢谢 汉内斯

这种设计为您提供了更大的灵活性。您可以在您的项目中使用不同的命名空间添加一个应用程序的两个实例(例如,不同类型用户的两个管理面板)。

此外,Django 在 url 中为应用程序提供了两种命名空间。应用程序命名空间与java中的包或C++中的命名空间相同,它是唯一的应用程序名称,您可以在模板中使用。

Django 也提供应用程序实例命名空间,正如您在示例中所写:

urlpatterns = patterns('',
    url(r'^polls/', include('polls.urls', namespace="polls")),
    url(r'^admin/', include(admin.site.urls)),
)

在此示例中,管理应用程序可通过应用程序命名空间 'admin' 访问,投票应用程序可通过应用程序实例命名空间 'pools' 访问,这显然是您定义的。

您可以在文档中阅读有关命名空间的更多信息: https://docs.djangoproject.com/en/1.7/topics/http/urls/#url-namespaces

application namespace

This describes the name of the application that is being deployed. Every instance of a single application will have the same application namespace. For example, Django’s admin application has the somewhat predictable application namespace of 'admin'.

instance namespace

This identifies a specific instance of an application. Instance namespaces should be unique across your entire project. However, an instance namespace can be the same as the application namespace. This is used to specify a default instance of an application. For example, the default Django admin instance has an instance namespace of 'admin'.

Url dispatcher 首先通过应用命名空间查找,然后如果没有匹配则在尝试反转 url 时通过实例命名空间查找: https://docs.djangoproject.com/en/1.7/topics/http/urls/#reversing-namespaced-urls