Django中几种重定向方法
这里使用的是django1.5
需求:有一个界面A,其中有一个formB,前台提交B之后,后台保存数据之后,返回界面A,如果保存失败需要在A界面提示错误。
这里就需要后台的重定向,而且需要可以带着参数,也就是errormessage
这里收集了几种方法,简答说下需要那些包,怎么简单使用。
一、使用HttpResponseRedirect
Thefirstargumenttotheconstructorisrequired–thepathtoredirectto.ThiscanbeafullyqualifiedURL(e.g.'http://www.yahoo.com/search/')oranabsolutepathwithnodomain(e.g.'/search/')。参数既可以使用完整的url,也可以是绝对路径。
fromdjango.httpimportHttpResponseRedirect @login_required defupdate_time(request): #pass ... form处理 returnHttpResponseRedirect('/commons/invoice_return/index/') #跳转到index界面
如果需要传参数,可以通过url参数
returnHttpResponseRedirect('/commons/invoice_return/index/?message=error') #跳转到index界面
这样在index处理函数中就可以get到错误信息。
二、redirect和reverse
fromdjango.core.urlresolversimportreverse fromdjango.shortcutsimportredirect #https://docs.djangoproject.com/en/1.5/topics/http/shortcuts/ @login_required defupdate_time(request): #pass ... form处理 returnredirect(reverse('commons.views.invoice_return_index',args=[])) #跳转到index界面
redirect类似HttpResponseRedirect的用法,也可以使用字符串的url格式/..inidex/?a=add
reverse可以直接用views函数来指定重定向的处理函数,args是url匹配的值。详细请参见文档
三、其他
其他的也可以直接在url中配置,但是不知道怎么传参数。
fromdjango.views.generic.simpleimportredirect_to
在url中添加(r'^one/$',redirect_to,{'url':'/another/'}),
我们甚至可以使用session的方法传值
request.session['error_message']='test' redirect('%s?error_message=test'%reverse('page_index'))
这些方式类似于location刷新,客户端重新指定url。
还没找到怎么在服务端跳转处理函数,直接返回response到客户端的方法。
2014-11-13研究:
是不是之前的想法太死板,重定向,如果需要携带参数,那么能不能直接调用views中url对应的方法来实现呢,默认指定一个参数。
例如view中有个方法baseinfo_account,然后另一个url(对应view方法为blance_account)要重定向到这个baseinfo_account。
url中的配置:
urlpatterns=patterns('', url(r'^baseinfo/','account.views.baseinfo_account'), url(r'^blance/','account.views.blance_account'), )
@login_required defbaseinfo_account(request,args=None): #按照正常的url匹配这么写有点不合适,看起来不规范 ifargs: printargs returnrender(request,'accountuserinfo.html',{"user":user}) @login_required defblance_account(request): returnbaseinfo_account(request,{"name":"orangleliu"})