這篇文章主要介紹了Django中幾種重定向方法,本文講解了使用HttpResponseRedirect、redirect、reverse以及配置文件中配置URL等方法,需要的朋友可以參考下
這里使用的是django1.5
需求: 有一個界面A,其中有一個form B, 前臺提交B之后,后臺保存數(shù)據(jù)之后,返回界面A,如果保存失敗需要在A界面提示錯誤。
這里就需要后臺的重定向,而且需要可以帶著參數(shù),也就是error message
這里收集了幾種方法,簡答說下需要那些包,怎么簡單使用。
一、 使用HttpResponseRedirect
The first argument to the constructor is required – the path to redirect to. This can be a fully qualified URL (e.g.'http://www.yahoo.com/search/') or an absolute path with no domain (e.g. '/search/')。 參數(shù)既可以使用完整的url,也可以是絕對路徑。
代碼如下:
from django.http import HttpResponseRedirect
@login_required
def update_time(request):
#pass ... form處理
return HttpResponseRedirect('/commons/invoice_return/index/') #跳轉(zhuǎn)到index界面
如果需要傳參數(shù),可以通過url參數(shù)
代碼如下:
return HttpResponseRedirect('/commons/invoice_return/index/?message=error') #跳轉(zhuǎn)到index界面
這樣在index處理函數(shù)中就可以get到錯誤信息。
二、 redirect和reverse
代碼如下:
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
#https://docs.djangoproject.com/en/1.5/topics/http/shortcuts/
@login_required
def update_time(request):
#pass ... form處理
return redirect(reverse('commons.views.invoice_return_index', args=[])) #跳轉(zhuǎn)到index界面
redirect 類似HttpResponseRedirect的用法,也可以使用 字符串的url格式 /..inidex/?a=add
reverse 可以直接用views函數(shù)來指定重定向的處理函數(shù),args是url匹配的值。 詳細(xì)請參見文檔
三、 其他
其他的也可以直接在url中配置,但是不知道怎么傳參數(shù)。
代碼如下:
from django.views.generic.simple import redirect_to
在url中添加 (r'^one/$', redirect_to, {'url': '/another/'}),
我們甚至可以使用session的方法傳值
復(fù)制代碼 代碼如下:
request.session['error_message'] = 'test'
redirect('%s?error_message=test' % reverse('page_index'))
這些方式類似于location刷新,客戶端重新指定url。
還沒找到怎么在服務(wù)端跳轉(zhuǎn)處理函數(shù),直接返回response到客戶端的方法。
2014-11-13 研究:
是不是之前的想法太死板,重定向,如果需要攜帶參數(shù),那么能不能直接調(diào)用views中 url對應(yīng)的方法來實現(xiàn)呢,默認(rèn)指定一個參數(shù)。
例如view中有個方法baseinfo_account, 然后另一個url(對應(yīng)view方法為blance_account)要重定向到這個baseinfo_account。
url中的配置:
復(fù)制代碼 代碼如下:
urlpatterns = patterns('',
url(r'^baseinfo/', 'account.views.baseinfo_account'),
url(r'^blance/', 'account.views.blance_account'),
)
復(fù)制代碼 代碼如下:
@login_required
def baseinfo_account(request, args=None):
#按照正常的url匹配這么寫有點不合適,看起來不規(guī)范
if args:
print args
return render(request, 'accountuserinfo.html', {"user": user})
@login_required
def blance_account(request):
return baseinfo_account(request, {"name": "orangleliu"})
需要測試為:
1 直接訪問 /baseinfo 是否正常 (測試ok)
2 訪問 /blance 是否能正常的重定向到 /baseinfo 頁面,并且獲取到參數(shù)(測試ok,頁面為/baseinfo 但是瀏覽器地址欄的url仍然是/blance)
這樣的帶參數(shù)重定向是可行的。
更多信息請查看IT技術(shù)專欄