美文网首页
Django中url的namespace

Django中url的namespace

作者: 傅恺男 | 来源:发表于2018-04-21 00:24 被阅读0次
  1. application namespace
    app的名称,一个app可以有多个实例,具有相同的application namespace
  2. instance namespace
    app的一个示例,在当前项目中应是唯一的
  3. default instance of application
    instance namespace与所属application namespace相同的实例
  4. current instance
    使用reverse()函数的current_app参数可以指定当前应用


    image.png
#urls.py
from django.conf.urls import include, url

urlpatterns = [
    url(r'^author-polls/', include('polls.urls', namespace='author-polls')),
    url(r'^publisher-polls/', include('polls.urls', namespace='publisher-polls')),
]
from django.urls import path

from . import views

app_name = 'polls'
urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
    path('<int:pk>/', views.DetailView.as_view(), name='detail'),
    ...
]
  1. 此时polls:index的namespace与当前app的application instance(及app_name)相匹配。如果其中一个实例是当前应用实例current,例如正在渲染author-polls的detail视图,polls:index将解析到author-polls实例的index页面。下面的两种方式的结果都是'/author-polls/'
    在类视图中:
    reverse('polls:index', current_app=self.request.resolver_match.namespace)
    在模板中:
    {% url 'polls:index' %}
  2. 如果没有当前实例current,例如在站点的其它地方渲染一个页面。polls:index将解析到polls中最后一个注册的实例中。因为没有默认实例(instance namespace为polls的实例),将使用polls注册的最后一个实例。在这里将解析到publisher-polls,因为它在urlpatterns的末尾
  3. 如果解析author-polls:index,将直接定位到author-polls的index页面。因为此时的namesapce是author-polls,不能与application namespace匹配,根据上面的流程将直接查找instance namespace
  4. 如果app还有一个名为polls的默认实例,上面的第二种情况polls:index将解析到该默认实例,而不是urlpatterns中最后声明的实例

相关文章

网友评论

      本文标题:Django中url的namespace

      本文链接:https://www.haomeiwen.com/subject/tpdtlftx.html