當(dāng)一個(gè)函數(shù)進(jìn)行完成后需要重定向到一個(gè)帶參數(shù)的url
URL
path('peopleapply/int:jobid>/',second_views.peopleapply,name='peopleapply'),
函數(shù)
def peopleapply(request,jobid):
略
調(diào)用
return redirect('peopleapply',jobid = people.jbnum_id)
peopleapply
為函數(shù)再url中的name
jobid
為需要的參數(shù)名稱
補(bǔ)充:DJANGO中多種重定向方法使用
本文主要講解使用HttpResponseRedirect、redirect、reverse以及配置文件中配置URL等重定向方法
本文使用了Django1.8.2
使用場景,例如在表單一中提交數(shù)據(jù)后,需要返回到另一個(gè)指定的頁面即可使用重定向方法
一、 使用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?!眳?shù)可以是絕對路徑跟相對路徑”
from django.http import HttpResponseRedirect
@login_required
def update_time(request):
#表單處理OR邏輯處理
return HttpResponseRedirect('/') #跳轉(zhuǎn)到主界面
#如果需要傳參數(shù)
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):
#進(jìn)行要處理的邏輯
return redirect(reverse('test.views.invoice_return_index', args=[])) #跳轉(zhuǎn)到index界面
redirect 類似HttpResponseRedirect的用法,也可以使用 字符串的url格式 /..index/?a=add reverse 可以直接用views函數(shù)來指定重定向的處理函數(shù),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。
四、
#重定向,如果需要攜帶參數(shù),那么能不能直接調(diào)用views中 url對應(yīng)的方法來實(shí)現(xiàn)呢,默認(rèn)指定一個(gè)參數(shù)。
#例如view中有個(gè)方法baseinfo_account, 然后另一個(gè)url(對應(yīng)view方法為blance_account)要重定向到這個(gè)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匹配這么寫有點(diǎn)不合適,看起來不規(guī)范
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頁面,并且獲取到參數(shù)(測試ok,頁面為/index但是瀏覽器地址欄的url仍然是/blance)
#這樣的帶參數(shù)重定向是可行的。
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。
您可能感興趣的文章:- Django中多種重定向方法使用詳解
- 深入了解Django View(視圖系統(tǒng))
- 詳解Django中views數(shù)據(jù)查詢使用locals()函數(shù)進(jìn)行優(yōu)化
- django多個(gè)APP的urls設(shè)置方法(views重復(fù)問題解決)
- django url到views參數(shù)傳遞的實(shí)例
- 對DJango視圖(views)和模版(templates)的使用詳解