有谁知道好的Django URL命名空间教程?

min*_*der 29 django django-urls

我正在为Django中的URL命名空间寻找一个很好的教程.我发现官方文档有点过于稀疏 - 它缺乏很好的例子.我在堆栈上发现了类似的问题,但答案并没有帮助我完全理解这个主题.

Dav*_*Eyk 33

同意,这方面的文件相当令人困惑.这是我对它的阅读(注意:所有代码都是未经测试的!):

apps.help.urls:

urlpatterns = [
    url(r'^$', 'apps.help.views.index', name='index'),
    ]
Run Code Online (Sandbox Code Playgroud)

在你的主要urls.py:

urlpatterns = [
    url(r'^help/', include('apps.help.urls', namespace='help', app_name='help')),
    url(r'^ineedhelp/', include('apps.help.urls', namespace='otherhelp', app_name='help')),
    ]
Run Code Online (Sandbox Code Playgroud)

在您的模板中:

{% url help:index %}
Run Code Online (Sandbox Code Playgroud)

应该产生网址/help/.

{% url otherhelp:index %}
Run Code Online (Sandbox Code Playgroud)

应该产生网址/ineedhelp/.

{% with current_app as 'otherhelp' %}
    {% url help:index %}
{% endwith %}
Run Code Online (Sandbox Code Playgroud)

同样应该产生网址/ineedhelp/.

同样,reverse('help:index')应该产生/help/.

reverse('otherhelp:index')应该产生/ineedhelp/.

reverse('help:index', current_app='otherhelp')同样应该产生/ineedhelp/.

就像我说的那样,这是基于我对文档的阅读以及我对Django-land中事物的运作方式的熟悉程度.我没有花时间来测试这个.