gpt4 book ai didi

python - Django 1.2 : login issue (GET parameter: next)

转载 作者:行者123 更新时间:2023-11-28 16:53:38 24 4
gpt4 key购买 nike

我有一个关于 django 的新问题(这些天我发布了一个丢失的问题^^)。

这是我的情况:我有一个自定义登录 View (在设置中注册为登录 url),我在其中对用户进行身份验证。我选择做一个自定义 View ,以便能够添加消息和日志记录。

身份验证工作正常,但我对 GET 参数“next”有疑问。它由重定向用户进行身份验证的 View 自动设置。在我看来,它用于在成功登录后重定向用户。

代码如下:

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))

当用户在已经通过身份验证(首先是其他)的情况下访问登录 View 时,下一个参数是正确的。

当匿名用户尝试访问/editor/25(例如)并被重定向到登录以进行身份​​验证时,即使出现在 url 中,“next”也始终为 None(它应该是“/editor/25”) .

某处应该有一个简单的错误。也许它与 authenticate() 或 login() (django.contrib.auth) 有关。

感谢您的帮助。

最佳答案

When an anonymous user tries to go to /editor/25 (for example) and is redirected to login for authentication, "next" is always None even if present in the url (it should be "/editor/25").

这听起来很奇怪。您能否检查该 URL 是否确实将 ?next=/editor/25/ 作为查询字符串?同时记录 request.GET 并查看结果。

此外,您可能希望从 request.GET 中获取 next 参数,并在呈现模板时将其作为(可选)隐藏输入包含在表单中。 auth 模块的 login View 执行此操作。这样,您的表单就可以在 POST 上从 request.POST 中获取 next

关于python - Django 1.2 : login issue (GET parameter: next),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3861840/

24 4 0