任何人都知道Django的URL命名空间教程? [英] Anyone knows good Django URL namespaces tutorial?

查看:200
本文介绍了任何人都知道Django的URL命名空间教程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

同意,这个文档比较混乱。这是我的阅读(注意:所有代码都是未经测试的):



apps.help.urls

  urlpatterns = [
url(r'^ $','apps.help .views.index',name ='index'),
]

在你的主 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'))
]

在您的模板中:

  {%url help:index%} 
/ pre>

应该产生url / help /

  {%url otherhelp:index%} 

应该生成url / ineedhelp /

  {%with current_app as' otherhelp'%} 
{%url help:index%}
{% endwith%}

应该同样产生url / ineedhelp /



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



reverse('otherhelp:index') code> / ineedhelp / 。



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



像我说的,这是基于在我阅读文档时,我现在对Django-land中的事情往往有所了解。我没有花时间来测试这个。


I'm looking for a good tutorial for URL namespaces in Django. I find official documentation a little too sparse - it lacks good examples. I found similar question here on stack, but the answers didn't help me to fully understand the subject either.

解决方案

Agreed, the docs for this are rather confusing. Here's my reading of it (NB: all code is untested!):

In apps.help.urls:

urlpatterns = [
    url(r'^$', 'apps.help.views.index', name='index'),
    ]

In your main 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')),
    ]

In your template:

{% url help:index %}

should produce the url /help/.

{% url otherhelp:index %}

should produce the url /ineedhelp/.

{% with current_app as 'otherhelp' %}
    {% url help:index %}
{% endwith %}

should likewise produce the url /ineedhelp/.

Similarly, reverse('help:index') should produce /help/.

reverse('otherhelp:index') should produce /ineedhelp/.

reverse('help:index', current_app='otherhelp') should likewise produce /ineedhelp/.

Like I said, this is based on my reading of the docs and my existing familiarity with how things tend to work in Django-land. I haven't taken the time to test this.

这篇关于任何人都知道Django的URL命名空间教程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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