在视图函数里面,如果你去直接通过response跳转url,是不可以,因为response只能返回参数列表
如果想要跳转页面,使用新的方法 HttpResponseRedirect
def text(request):
return HttpResponseRedirect('/App/hello/')
但是里面只能传固定地址值
如果想要通过动态获取(反向解析)的方式传参,需要新的方法 reverse() 导Django的包
def text(request):
return HttpResponseRedirect(reverse("fan:bingbing"))
反向解析配置:
在App目录下配置urls 需要给他一个name属性 name = "名字自定义":
例如:http://127.0.0.1:8080/App/getstudent/
url(r'^getstudent/',views.getstudent,name='game')
反向解析传参配置,即访问url时需带相应的正则匹配参数:
例如:http://127.0.0.1:8080/App/getstudent/2018/09/
l(r'^getstudent/(?P<year>\d+)/(?P<month>\d+)/',views.getstudent,name='game'):
相应的当浏览器访问url时,在Views层的写法如下:
def getstudent(request,year,month):
return render(request,'person.html',context={'date':year +'-'+ month })
举例详解Url反向解析过程及原理:
1、首先在urls.py文件中编写代码:
url(r'^move/',views.move),
url(r'^getstudent/(?P<year>\d+)/(?P<month>\d+)/',views.getstudent,name='game'),
2、在views.py文件中编写访问方法:
def move(request):
return render(request,'word.html')
3、建立一个上步骤定义的Html文件——word.html;并通过第一步中为相关url添加的name方法,编写一行反向解析带参url代码如下:
<a href="{% url 'game' year=2018 month=09 %}">点击启动WrGame</a>
4、在views.py文件中编写用于加载渲染,解析的Url的代码:
def getstudent(request,year,month):
return render(request,'person.html',context={'date':year +'-'+ month })
其实现过程就是要当客户访问 http://127.0.0.1:8080/App/move/路径时,通过加载渲染此路径下的方法得到实际访问的URL地址————即 http://127.0.0.1:8080/App/getperson/ (http://127.0.0.1:8080/namespace/name)
实现过程
在浏览器输入访问的地址:得到的是在当前url下渲染定义的HTML下的页面:
点击此超链接,通过URL反向解析方法得到我们所访问的页面: