命名空间 namespace
由于name没有作用域,Django在反解URL时,会在项目全局顺序搜索,当查找到第一个name指定URL时,立即返回
我们在开发项目时,会经常使用name属性反解出URL,当不小心定义相同的name时,可能会导致URL反解错误,为了避免这种事情发生,引入了命名空间
使用Django提供namespace参数
from django.conf.urls import url,include #将视图包含进来,并使用命名空间 urlpatterns = [ url(r'^aaa', include("app01.urls"),namespace='aaa')), url(r'^bbb', include("app02.urls"),namespace='bbb')), ]
#创建app01视图
from django.conf.urls import url from app01 import views app_name = "app01" urlpatterns = [ url(r'aaa/$', views.aaa, name="index"), ]
def aaa(request): return HttpResponse(reverse("app01:index"))
#创建app02视图,使他们拥有同样的name属性
from django.conf.urls import url from app01 import views app_name = "app02" urlpatterns = [ url(r'aaa/$', views.aaa, name="index"), ]
def aaa(request): return HttpResponse(reverse("app02:index"))
输出结果
#http://127.0.0.1/aaa/aaa/ # 结果: # /aaaaaa/
#http://127.0.0.1/bbb/aaa/
# 结果: # /bbbaaa/