我有一个关于 django 的新问题(这些天我发布了一个丢失的问题^^)。
这是我的情况:我有一个自定义登录视图(在设置中注册为登录 url),我在其中对用户进行身份验证。我选择创建自定义视图以便能够添加消息和日志记录。
身份验证工作正常,但我对 GET 参数“next”有问题。它是由重定向用户进行身份验证的视图自动设置的。在我看来,它用于在成功登录后重定向用户。
这是代码:
from django.http import HttpResponse
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.utils.translation import ugettext as _
from django.contrib import messages
from django.template import RequestContext
from django.contrib.auth import authenticate, login, logout
import logging
logger = logging.getLogger("views")
def login_user(request):
"""
Displays the login form or authenticates the user if called by POST.
"""
accepted = False
next = request.GET.get('next', None)
if not request.user.is_authenticated():
if request.POST:
# Get the form data and check the user credentials
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
# Log the user in
login(request, user)
logger.info("Login of user : %s", user.username)
# Confirm the login
messages.success(request,_('Login successful. Welcome !'))
accepted = True
else:
messages.error(request,_('This account has been disabled by the administrator.'))
else:
messages.warning(request,_('The given username or password is invalid. Please try again.'))
else:
# If already authenticated
accepted = True
# Choose where to go
if accepted:
return HttpResponse(next)
if next:
return HttpResponseRedirect(next)
else:
return HttpResponseRedirect(reverse('myview'))
else:
return render_to_response('login.html',
context_instance=RequestContext(request))
当用户在已经通过身份验证(首先是其他)的情况下访问登录视图时,下一个参数是正确的。
当匿名用户尝试访问 /editor/25(例如)并被重定向到登录进行身份验证时,“next”始终为 None,即使存在于 url 中(应为“/editor/25”)。
某处应该有一个简单的错误。也许它与authenticate()或login()(django.contrib.auth)有关。
感谢您的帮助。