django怎样实现视图重定向

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

django怎样实现视图重定向

  2021-04-03 我要评论

当请求访问到某个视图时,我们想让它重定向到其他页面,应该怎么做呢?

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")
您可能感兴趣的文章:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们