标签:authentication login python django
我有一个关于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并重定向到登录进行身份验证时,即使URL中存在“下一个”,也始终为“无”(应为“ / 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中获取下一个参数,并在呈现模板时将其作为(可选)隐藏输入包含在表单中. auth模块的登录视图执行此操作.这样,您的表单就可以从request.POST上的POST中提取.
标签:authentication,login,python,django 来源: https://codeday.me/bug/20191209/2096306.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。