1. 程式人生 > >[Django]幾種重定向的方式

[Django]幾種重定向的方式

這裡使用的是django1.5

需求: 有一個介面A,其中有一個form B, 前臺提交B之後,後臺儲存資料之後,返回介面A,如果儲存失敗需要在A介面提示錯誤。

這裡就需要後臺的重定向,而且需要可以帶著引數,也就是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/')。 引數既可以使用完整的url,也可以是絕對路徑。

from django.http import HttpResponseRedirect
 
@login_required
def update_time(request):
    #pass  ...   form處理
    return HttpResponseRedirect('/commons/invoice_return/index/')  #跳轉到index介面


如果需要傳引數,可以通過url引數

return HttpResponseRedirect('/commons/invoice_return/index/?message=error')  #跳轉到index介面
這樣在index處理函式中就可以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=[]))  #跳轉到index介面

redirect 類似HttpResponseRedirect的用法,也可以使用 字串的url格式 /..inidex/?a=add

reverse 可以直接用views函式來指定重定向的處理函式,args是url匹配的值。 詳細請參見文件

三、 其他

其他的也可以直接在url中配置,但是不知道怎麼傳引數。

from django.views.generic.simple import redirect_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
def baseinfo_account(request, args=None):
    ​#按照正常的url匹配這麼寫有點不合適,看起來不規範
    ​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 頁面,並且獲取到引數(測試ok,頁面為/baseinfo 但是瀏覽器位址列的url仍然是/blance)

這樣的帶引數重定向是可行的。

本文出自 orangleliu筆記本 部落格,請務必保留此出處 http://blog.csdn.net/orangleliu/article/details/38347863