不使用命名空间,且两个APP某条url使用相同的name属性
app01_urls.py
1 urlpatterns = [ 2 url(r'aaa/$', views.app01_aaa, name="index"), 3 ]
app02_urls.py
1 urlpatterns = [ 2 url(r'aaa/$', views.app02_aaa, name="index"), 3 ]
各自的函数中同时反解URL
#app01.views def aaa(request): return HttpResponse(reverse("index")) #app02.views def aaa(request): return HttpResponse(reverse("index"))
页面显示结果app01.views
1 #app01 2 3 /app01aaa/ 4 5 6 #app02 7 8 /app01aaa/
总结
由于name没有作用域,Django在反解URL时,会在项目全局顺序搜索,当查找到第一个name指定URL时,立即返回
我们在开发项目时,会经常使用name属性反解出URL,当不小心定义相同的name时,可能会导致URL反解错误,为了避免这种事情发生,引入了命名空间
解决
使用Django提供namespace参数
使用命名空间
app.urls必须添加变量
1 app_name = 'app01'
project_urls.py
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_urls.py
from django.conf.urls import url from app01 import views app_name = "app01" urlpatterns = [ url(r'aaa/$', views.aaa, name="index"), ]
app02_urls.py
from django.conf.urls import url from app01 import views app_name = "app02" urlpatterns = [ url(r'aaa/$', views.aaa, name="index"), ]
app01_views.py
def aaa(request): return HttpResponse(reverse("app01:index"))
app02_views.py
def aaa(request): return HttpResponse(reverse("app02:index"))
验证
1 #http://127.0.0.1/aaa/aaa/ 2 3 # 结果: 4 # /aaaaaa/ 5 6 7 #http://127.0.0.1/bbb/aaa/ 8 9 # 结果: 10 # /bbbaaa/
出处:https://www.cnblogs.com/cq146637/p/7806336.html