django命名url与url反向解析

1.urls.py路由中指定别名

2.views.py视图文件中导入from django.shortcuts import render, redirect, reverse

3.也可从这里导入:from django.urls import  reverse

命名URL:

 普通命名 url(r'^class/$', views.class, name=’cla’ )

    分组命名 url(r'^class/([0-9]{4})/([0-9]{2})/$', views.class, name=’cla’ )

    命名分组 url(r'^class/(?P<x>[0-9]{4})/(?P<y>[0-9]{2})/$', views.class, name=’cla’ )

URL反向解析:

    在视图函数中的语法:  views.py中导入from django.urls import  reverse

        普通: redirect( reverse(‘cla’) )  # 会动态的感知cla对应的url中正则的变化,并体现出来

        分组: redirect( reverse(‘cla’ , args=(‘6666’, ’88’) ) )  # 有参正则给的参数要符合正则规则

        命名: redirect( reverse(‘cla’ , kwargs={ ‘x’:‘6666’, ’y’: ’88’} ) )  # 同上

    html模板中的语法:

        普通: {% url ‘cla’ %}  # url 后跟别名即可,会动态感知并替换

        分组: {% url ‘cla’ ‘6666’ ‘88’ %}  # 原理同上视图中

        命名: {% url ‘cla’ x=‘6666’ y=‘88’ %}

. 项目中存在多个包,且包内别名有重复时:

      以下是项目目录下的主路由语法, 其中namespace是固定写法,不可变

      url(r'app02/', include('app02.urls',namespace='app02')),

      url(r'app01/',include('app01.urls',namespace='app01')),

以下是views.py中函数视图内的语法:

reverse('app01:home',kwargs={'year':'2018','month':'10'})

reverse('app02:home',kwargs={'year':'2018','month':'10'})

以下是html页面中的语法:

{% url 'app02:home' '2018' '10'  %}

猜你喜欢

转载自www.cnblogs.com/quzq/p/9905066.html