Django中多种重定向方法使用详解

yipeiwu_com6年前Python基础

前言

本文使用了Django1.8.2

使用场景,例如在表单一中提交数据后,需要返回到另一个指定的页面即可使用重定向方法

一、 使用HttpResponseRedirect

fuhao The first argument to the constructor is required – the path to redirect to. This can be a fully qualified URL or an absolute path with no domain。”参数可以是绝对路径跟相对路径”

from django.http import HttpResponseRedirect 

@login_required 
def update_time(request): 
  #表单处理OR逻辑处理 
  return HttpResponseRedirect('/') #跳转到主界面 
#如果需要传参数
return HttpResponseRedirect('/commons/index/?message=error')

二 redirect和reverse

from django.core.urlresolvers import reverse 
from django.shortcuts import redirect 
#https://docs.djangoproject.com/en/1.8.2/topics/http/shortcuts/ 

@login_required 
def update_time(request): 
  #进行要处理的逻辑 
  return redirect(reverse('test.views.invoice_return_index', args=[])) #跳转到index界面 

redirect 类似HttpResponseRedirect的用法,也可以使用 字符串的url格式 /..index/?a=add
reverse 可以直接用views函数来指定重定向的处理函数,args是url匹配的值。

三、 其他

#其他的也可以直接在url中配置
from django.views.generic.simple import redirect_to 
在url中添加 (r'^test/$', redirect_to, {'url': '/author/'}), 

#我们甚至可以使用session的方法传值
request.session['error_message'] = 'test' 
redirect('%s?error_message=test' % reverse('page_index')) 
#这些方式类似于刷新,客户端重新指定url。

#重定向,如果需要携带参数,那么能不能直接调用views中 url对应的方法来实现呢,默认指定一个参数。
#例如view中有个方法baseinfo_account, 然后另一个url(对应view方法为blance_account)要重定向到这个baseinfo_account。
#url中的配置:
urlpatterns = patterns('', 
  url(r'^index/', 'account.views.index_account'), 
  url(r'^blance/', 'account.views.blance_account'), 
) 
# views.py
@login_required 
def index_account(request, args=None): 
  ​#按照正常的url匹配这么写有点不合适,看起来不规范 
  ​if args: 
    print args 
  return render(request, 'accountuserinfo.html', {"user": user}) 


@login_required   
def blance_account(request): 
  return index_account(request, {"name": "orangleliu"}) 
#测试为:
#1 直接访问 /index 是否正常 (测试ok)
#2 访问 /blance 是否能正常的重定向到 /index页面,并且获取到参数(测试ok,页面为/index但是浏览器地址栏的url仍然是/blance)
#这样的带参数重定向是可行的。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

余弦相似性计算及python代码实现过程解析

余弦相似性计算及python代码实现过程解析

A:西米喜欢健身 B:超超不爱健身,喜欢打游戏 step1:分词 A:西米/喜欢/健身 B:超超/不/喜欢/健身,喜欢/打/游戏 step2:列出两个句子的并集 西米/喜欢/健身/超...

取numpy数组的某几行某几列方法

这个操作在numpy数组上的操作感觉有点麻烦,但是也没办法。 例如 a = [[1,2,3], [4,5,6], [7,8,9]] 取 a 的 2 3 行, 1 2 列...

pandas实现DataFrame显示最大行列,不省略显示实例

如下所示: import pandas as pd #显示所有列 pd.set_option('display.max_columns', None) #显示所有行 pd.set_...

Python中Threading用法详解

Python的threading模块松散地基于Java的threading模块。但现在线程没有优先级,没有线程组,不能被销毁、停止、暂停、开始和打断。 Java Thread类的静态方法...

6行Python代码实现进度条效果(Progress、tqdm、alive-progress​​​​​​​和PySimpleGUI库)

6行Python代码实现进度条效果(Progress、tqdm、alive-progress​​​​​​​和PySimpleGUI库)

在项目开发过程中加载、启动、下载项目难免会用到进度条,如何使用Python实现进度条呢? 这里为小伙伴们分享四种Python实现进度条的库:Progress库、tqdm库、alive-p...