django如何实现视图重定向
作者:苦瓜爆炒牛肉 发布时间:2022-05-28 12:22:13
标签:django,视图,重定向
当请求访问到某个视图时,我们想让它重定向到其他页面,应该怎么做呢?
1.HttpResponseRedirect
需求:当我们访问127.0.0.1/my_redirect时跳到127.0.0.1/user/index
注意:要注册相应的url
def my_redirect(request):
return HttpResponseRedirect('/user/index')
2.redirect
需求:同上
def my_redirect(request):
return redirect('/user/index')
3.reversr函数动态生成url地址,解决硬编码维护麻烦的问题(用得较少)
如果你写的视图函数,有一大堆都是重定向到127.0.0.1/user/index的。
那么当你想要改一下它的重定向地址时,让他重定向到127.0.0.1/user/abc。就要一个一个视图函数修改了。这样维护起来是不是特别的麻烦?reverse函数自动生成url地址就可以解决这个问题啦。
(1)当我们在项目的urls.py文件和应用的urls.py文件都设置了url。
项目中的urls.py:
url(r'^user/',include("user.urls",namespace="user")),
url(r'^my_redirect',views.my_redirect)
应用的urls.py:
url(r'^index$',views.index,name="index")
视图:
# 重定向
def my_redirect(request):
url=reverse("user:index") # 先写namespace的值,再写name的值!
return redirect(url)
现在的情形是访问127.0.0.1/my_redirect,直接重定向到127.0.0.1/user/index。
如果想重定向到127.0.0.1/user/abc的话,直接修改应用的urls.py为:
url(r'^abc$',views.my_redirect,name="index")
如果想重定向到127.0.0.1/abc/index的话,直接修改项目的urls.py为:
url(r'^abc/',include("user.urls",namespace="user"))
(2)当我们只在项目的urls.py设置了url。
项目中的urls.py:
url(r'^index',views.index,name="index"),
url(r'^my_redirect$',views.my_redirect)
视图:
# 重定向
def my_redirect(request):
url=reverse("index")
return redirect(url)
现在的情形是访问127.0.0.1/my_redirect时自动跳转到127.0.0.1/index。
如果想重定向到127.0.0.1/abc时,直接修改项目中的urls.py文件为:
url(r'^abc',views.index,name="index")
来源:https://www.cnblogs.com/chichung/p/9880519.html
0
投稿
猜你喜欢
- 目录前言环境依赖代码前言本文主要分享一个可以将图片或者视频模糊化的工具代码。技术路线主要是使用ffmpeg滤镜。环境依赖ffmpeg环境部署
- 在利用tensorflow进行文本挖掘工作的时候,经常涉及到维度扩展和压缩工作。比如对文本进行embedding操作完成之后,若要进行卷积操
- 第一种:import socket import fcntl import struct def get_ip_address(ifname
- 1. 什么是数据不平衡所谓的数据不平衡(imbalanced data)是指数据集中各个类别的数量分布不均衡;不平衡数据在现实任务中十分的常
- 用过QQ的人应该都知道软键盘,他可以增强我们密码的安全性,以保证我们的密码资料不被非法监听。现在软键盘也用在了很多的网站上,像早期银行的在线
- 本文实例讲述了Python实现的列表排序、反转操作。分享给大家供大家参考,具体如下:排序:使用sorted方法和列表的sort方法:sort
- 代码实现的目的:为一个自定义的类的某个属性在使用它时候,触发某个事件。 该程序的效果:点击输入按钮,弹出一个脚本提示输入框让用户输入他的姓名
- 看了OReilly.JavaScript.The.Definitive.Guide.5th.Edition.Aug.2006里的cookie
- 本文实例讲述了Python编程实现数学运算求一元二次方程的实根算法。分享给大家供大家参考,具体如下:问题:请定义一个函数quadratic(
- 什么是内存管理机制python中创建的对象的时候,首先会去申请内存地址,然后对对象进行初始化,所有对象都会维护在一个叫做refchain的双
- 字典的常用方法方便举例,先创建2个字典list_test={"bob":19,"aoa":18,&q
- 1、PIL介绍以及图片分割Python 3 安装: pip3 install Pillow1.1 image 模块Image模块
- 1.安装ubuntu有uwsgi的ppa:add-apt-repository ppa:stevecrozz/ppa apt-get upd
- 对于MySQL数据库,如果你要使用事务以及行级锁就必须使用INNODB引擎。如果你要使用全文索引,那必须使用myisam。 INNODB的实
- 句柄(handle)是C++程序设计中经常提及的一个术语。它并不是一种具体的、固定不变的数据类型或实体,而是代表了程序设计中的一个广义的概念
- 以下为SQL SERVER7.0以上版本的字段类型说明。SQL SERVER6.5的字段类型说明请参考SQL SERVER提供的说明。bit
- 根据国务院文件,5.19-5.21为全国哀悼日,在此期间,全国和各驻外机构下半旗志哀,停止公共娱乐活动,外交部和我国驻外使领馆设立吊唁簿。5
- “你不必严格遵守这些原则,违背它们也不会被处以宗教刑罚。但你应当把这些原则看成警铃,若违背了其中的一条,那么警铃就会响起
- 最近,小明为了达成小姐姐的愿望,在某宝买到心仪的宝贝,再加上又迷上了python,就通过python轻而易举地实现了(个人声明:对Java来
- 个人网站如有会员注册模块+动网论坛的话,那网站要与动网论坛系统整合,实现不同Web系统之间的用户信息同步更新、登录等操作就不是件容易的事了,