[英]Django 1.2: login issue (GET parameter: next)
我有一个关于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)有关。
谢谢你的帮助。
当匿名用户尝试转到/ editor / 25(例如)并重定向到登录进行身份验证时,“next”始终为None,即使在url中存在(它应该是“/ editor / 25”)。
这听起来很奇怪。 你能检查一下URL确实有?next=/editor/25/
作为查询字符串? 同时记录request.GET
,看看会发生什么。
此外,您可能希望从request.GET
获取next
参数,并在呈现模板时将其作为(可选)隐藏输入包含在表单中。 auth模块的login
视图执行此操作。 通过这种方式,您的表单可以从POST
request.POST
next
。
以下是类似问题的示例解决方案:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.