Django学习笔记(六):反向解析

反向解析

根据命名空间和url名字找到对应的处理逻辑

使用方法

1,在工程的urls.py

导入include方法 加入namespce来定义你的命名空间

url(r'^study05/',include("study05.url",namespace="study05"))

(第一个"study05"用于路径使用,例如:localhost:12345/study/lolstu

第二个"study05"是指app项目的名称:

第三个"study05"用于反向解析,例如<a href="{% url ''study:lolstu"%})">

2,在项目的url.py里加入name参数 给url指定一个名字

url(r"^lolstu$",lolstu,name="lolstu")

(第一个"lolstu"用于路径使用,例如:localhost:12345/study/lolstu(先总路由再分路由)

第二个"lolstu"是指调用了views.py里的lolstu方法,例如 def lolstu(req):

第三个"lolstu"用于反向解析,例如<a href="{% url ''study:lolstu"%})">

3,前端

{%url '命名空间的名字:url的名字'%}

4,后端

    def index(req):
        return HttpResponseRedirect(reverse('python1803:czn'))
        解释:HttpResponseRedirect 是重定向 
             reverse('命名空间的名字:url的名字')

实例运用

解析url路径里面的参数,去数据库对应老师

1,先去允许url写成可变的

url(r"teacher/(?P<t_id>\d+)/(?P<a_id>\d+)", get_teacher, name='zhangsan'),

2,views.py里对应的处理请求函数要加入对应参数的占位

def get_teacher(req, t_id, a_id):
    正常写

前端写法:{%url 'python1803:zhangsan' t_id=2 a_id=3%}

后端写法: return HttpResponseRedirect(reverse('python1803:zhangsan', kwargs={'a_id':3, 't_id': 1}))

猜你喜欢

转载自blog.csdn.net/xiaohuoche175/article/details/81264327
今日推荐