我已經在幾個頁面中創建了登錄頁面強制登錄。現在,我需要在成功登錄後重新導向上一頁。登錄後重定向回到上一頁(Django)
當我強制登錄@login_required(login_url='/login/')
。它包括查詢字符串中的next
參數。
我試着用redirect_to = request.REQUEST.get('next', '')
抓住它,並把它重定向return HttpResponseRedirect(redirect_to)
,但沒有奏效。
view.py
def login(request):
def errorHandle(error):
form = LoginForm()
return render_to_response('login/login.html', {
'error' : error,
'form' : form,
})
if request.method == 'POST': # If the form has been submitted...
form = LoginForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
username = request.POST['username']
password = request.POST['password']
redirect_to = request.REQUEST.get('next', '')
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
# Redirect to a success page.
auth_login(request, user)
return HttpResponseRedirect(redirect_to)
# return render_to_response('login/logged_in.html', {
# 'username': username,
# })
else:
# Return a 'disabled account' error message
error = u'Account Disabled'
return errorHandle(error)
else:
# Return an 'invalid login' error message.
error = u'Invalid Login'
return errorHandle(error)
else:
error = u'Form is Invalid'
return errorHandle(error)
else:
form = LoginForm() # An unbound form
return render_to_response('login/login.html', {
'form': form,
})
模板
<div id="login_form">
<form action="." method="post">
{{ form.as_p }}
<input type="submit" value="Login">
</form>
</div>
編輯 - 我發現這個問題。這是我的模板問題。下面的表格工作正常。
<form action="" method="post">
<label for="username">User name:</label>
<input type="text" name="username" value="" id="username">
<label for="password">Password:</label>
<input type="password" name="password" value="" id="password">
<input type="submit" value="Login" id="button"/>
<input type="hidden" name="next" value="{{ next|escape }}" />
</form>
爲什麼不使用內置的[登錄](https://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.views.login)視圖?爲什麼不至少[看看它的代碼](https://code.djangoproject.com/browser/django/trunk/django/contrib/auth/views.py#L25)看看它是如何進行重定向的? – DrTyrsa 2012-04-03 07:53:08
@DTTyrsa我不知道如何使用內置登錄:/你可以發現這個代碼的問題? – ChamingaD 2012-04-03 08:14:37
你有沒有閱讀[文檔](https://docs.djangoproject.com/en/dev/topics/auth/)auth?那裏有什麼不清楚的地方? – DrTyrsa 2012-04-03 08:28:15