Python Django 1.2:登录问题(获取参数:next)
我有一个关于django的新问题(这些天我贴了一张丢失的^^) 以下是我的情况:我有一个自定义登录视图(在设置中注册为登录url),在这里我对用户进行身份验证。我选择做一个自定义视图,以便能够添加消息和日志记录 身份验证工作正常,但GET参数“next”有问题。它由重定向用户进行身份验证的视图自动设置。在我的视图中,它用于在成功登录后重定向用户 代码如下:Python Django 1.2:登录问题(获取参数:next),python,django,authentication,login,Python,Django,Authentication,Login,我有一个关于django的新问题(这些天我贴了一张丢失的^^) 以下是我的情况:我有一个自定义登录视图(在设置中注册为登录url),在这里我对用户进行身份验证。我选择做一个自定义视图,以便能够添加消息和日志记录 身份验证工作正常,但GET参数“next”有问题。它由重定向用户进行身份验证的视图自动设置。在我的视图中,它用于在成功登录后重定向用户 代码如下: from django.http import HttpResponse from django.core.urlresolvers imp
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/
作为查询字符串吗?同时记录请求。获取并查看结果
此外,您可能希望从请求中提取下一个
参数。获取
,并在呈现模板时将其作为(可选)隐藏输入包含在表单中。auth模块的登录
视图执行此操作。通过这种方式,您的表单可以从请求中选择下一个。在POST
上发布下面是一个类似问题的示例解决方案:
这真的很奇怪。我将尝试记录请求。明天获取并检查url,我现在不在工作(日本时间)。从邮局取走它有什么意义?实际上我不能,因为用户被重定向到页面,而值为None。我在文档中找不到关于这个问题的任何信息。现在我想你可能是对的,下一个不是随表单一起提交的,它解释了为什么只有提交表单的用户(匿名用户)才会这样做。对不起,我应该看看django的资料,这是一个很好的观点;不混合使用GET和POST可能是正确的,但他们肯定应该警告,将next作为GET参数传递将不起作用,因此应该将其内置到登录模板中。