django如何实现视图重定向

爱蒂网

django如何实现视图重定向

2020-03-15 19:31:44 分类 / 代码专栏 来源 / 互联网

这篇文章主要介绍了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")

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持爱蒂网。

猜你喜欢