Django: Multiple url patterns starting at the root spread across files

天大地大妈咪最大 提交于 2019-12-18 14:18:27

问题


I am wondering if it is possible to have the standard url patterns spread across multiple files (in this case the project-wide urls.py and several apps-specific urls.py).

Imagine that the project urls.py look like this (got this working):

from django.conf.urls import patterns, include, url
admin.autodiscover()

urlpatterns = patterns('',
    url(r'^user/signup/', 'registration.views.signup'),
    url(r'^user/confirm/(?P<code>\w{20})/', 'registration.views.confirm'),
    url(r'^user/profile/(\d+)/', 'profile.views.show'),
    url(r'^user/profile/edit/', 'profile.views.edit'), 
)

As you can see, I have two different apps that both want to user the urls for /user/*, so I can't just use r'^user/' with an include.

My question is: Can I split the above into two seperate urls.py files, that each go into their respective app?

Note: Disregard any syntax mistakes as this was typed in


回答1:


Sure. URLs are processed in order, and two includes can have the same prefix - if one doesn't succeed in matching, processing will just move on to the next one.

urlpatterns = patterns('',
    url(r'^user/', include('registration.urls')),
    url(r'^user/', include('profile.urls')),
)



回答2:


Also i suggest to add a namespace like this:

urlpatterns = patterns('',
    url(r'^user/', include('registration.urls', namespace="registration")),
    url(r'^user/', include('profile.urls', namespace="profile")),
)


来源:https://stackoverflow.com/questions/11618105/django-multiple-url-patterns-starting-at-the-root-spread-across-files

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