由于name没有作用域,Django在反解URL时,会在项目全局顺序搜索,当查找到第一个name指定URL时,立即返回。
project/urls.py
urlpatterns = [ path('admin/', admin.site.urls), path('app/', include('app.urls')), path('app2/', include('app2.urls')), path('app3/', include('app3.urls')), ]
app/urls.py
urlpatterns = [ path('index/', views.index, name='index'), ]
app2/urls.py
urlpatterns = [ path('index/', views.index, name='index'), ]
app3/urls.py
urlpatterns = [ path('index/', views.index, name='index'), ]
在各自的函数中同时反解url
# app/views def index(request): return HttpResponse(reverse('index')) # app2/views def index(request): return HttpResponse(reverse('index')) # app3/views def index(request): return HttpResponse(reverse('index'))
执行结果
http://127.0.0.1:8000/app/index/ /app3/index/ http://127.0.0.1:8000/app2/index/ /app3/index/ http://127.0.0.1:8000/app3/index/ /app3/index/
可以看到,当在不同的app的urls中定义相同的name时,最后反解出来的都是最后定义的一个URL,为了避免这种情况,Django引入了名称空间。
Django 2版本
project/urls.py
urlpatterns = [ path('admin/', admin.site.urls), path('app/', include(('app.urls', 'app'))), # include传入一个元组,第二个元素是app的名字 path('app2/', include(('app2.urls', 'app2'))), path('app3/', include(('app3.urls', 'app3'))), ]
app/urls.py
urlpatterns = [ path('index/', views.index, name='index'), ]
app2/urls.py
urlpatterns = [ path('index/', views.index, name='index'), ]
app3/urls.py
urlpatterns = [ path('index/', views.index, name='index'), ]
在各自的函数中同时反解url
# app/views def index(request): return HttpResponse(reverse('app:index')) # app2/views def index(request): return HttpResponse(reverse('app2:index')) # app3/views def index(request): return HttpResponse(reverse('app3:index'))
运行结果
http://127.0.0.1:8000/app/index/ /app/index/ http://127.0.0.1:8000/app2/index/ /app2/index/ http://127.0.0.1:8000/app3/index/ /app3/index/
成功地避免反解出错的问题