Python 在用户登录期间,Authenticate返回用户名和密码正确的None
我的用户登录在身份验证过程中有一些问题。 我正在使用Django 1.9和Python 3.6 用户=验证(用户名=用户名,密码=密码) 将用户返回为无 这就是myAccounts/views.py查找登录名的方式Python 在用户登录期间,Authenticate返回用户名和密码正确的None,python,django,login,django-templates,django-login,Python,Django,Login,Django Templates,Django Login,我的用户登录在身份验证过程中有一些问题。 我正在使用Django 1.9和Python 3.6 用户=验证(用户名=用户名,密码=密码) 将用户返回为无 这就是myAccounts/views.py查找登录名的方式 def register(request): registered = False if request.method == 'POST': reg_form = RegistrationForm(data=request.POST) profile_form =
def register(request):
registered = False
if request.method == 'POST':
reg_form = RegistrationForm(data=request.POST)
profile_form = UserProfileForm(data=request.POST)
if reg_form.is_valid() and profile_form.is_valid():
user = reg_form.save()
# print('before set password = ', user.password)
user.set_password(user.password)
# print('after set password = ', user.password)
user.save()
print(user.password)
profile = profile_form.save(commit=False)
profile.user = user
profile.email = user.email
profile.first_name = user.first_name
profile.last_name = user.last_name
if 'profile_pic' in request.FILES:
profile.profile_pic = request.FILES['profile_pic']
print('uploading pic .....')
profile.save()
args = {'reg_form': reg_form, 'profile_form': profile_form, 'registered': True}
head_list.update(args)
return render(request, 'registration.html', head_list)
else:
print(reg_form.errors, profile_form.errors)
args = {'reg_form': reg_form.errors, 'profile_form': profile_form.errors, 'registered': False}
head_list.update(args)
return render(request, 'registration.html', head_list, args)
else:
reg_form = RegistrationForm()
profile_form = UserProfileForm()
args = {'reg_form': reg_form, 'profile_form': profile_form, 'registered': False}
head_list.update(args)
print(head_list)
return render(request, 'registration.html', head_list)
def login_view(request):
params = {}
params.update(csrf(request))
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
# First get the username and password supplied
# username = request.POST.get('username', '')
# password = request.POST.get('password', '')
# Django's built-in authentication function:
print(username, password)
user = authenticate(username=username, password=password)
print('after aunthenticate', user)
# If we have a user
if user:
# Check it the account is active
if user.is_active:
# Log the user in.
login(request, username)
# Send the user back to some page.
# In this case their homepage.
# return HttpResponseRedirect(reverse('/user_login/'))
return render_to_response('user_login.html', RequestContext(request, {}))
else:
# If account is not active:
return HttpResponse("Your account is not active.")
else:
print("Someone tried to login and failed.")
print("They used username: {} and password: {}".format(username, password))
return HttpResponse("Invalid login details supplied.")
else:
form = LoginForm()
args = {'form': form}
head_list.update(args)
# Nothing has been provided for username or password.
return render(request, 'login.html', head_list)
login.html页面如下所示
{% block content %}
<section class="container">
<h1>LiquorApp Login Console</h1>
<div class="login">
<h1>Login to WebApp</h1>
<form method="post" action="/user_login/">
{% csrf_token %}
{{ form.as_p }}
{% comment %}Username: <input type="text" name="username" value="" size="50" />
<br />{% endcomment %}
{% comment %}<p><input type="text" name="username" value="" id="username" placeholder="username"></p>
<p><input id ="password" type="password" name="password" value="" placeholder="password"></p>
<p class="remember_me">{% endcomment %}
<label>
<input type="checkbox" name="remember_me" id="remember_me">
Remember me on this computer
</label>
</p>
<p class="submit"><input type="submit" name="commit" value="Login"></p>
</form>
</div>
</section>
{% endblock %}
除去
user.set_password(user.password)
从Accounts.views.register在Django 1.11中调用
身份验证(username=user.username,password=password,request=request)之前,确保user.is\u active为True
它在Django 1.8中运行良好,但在LTS 1.8和LTS 1.11之间的某个地方,他们为用户添加了一个额外的检查。在modelbend
类中是否处于活动状态:
class ModelBackend(object):
"""
Authenticates against settings.AUTH_USER_MODEL.
"""
def authenticate(self, request, username=None, password=None, **kwargs):
if username is None:
username = kwargs.get(UserModel.USERNAME_FIELD)
try:
user = UserModel._default_manager.get_by_natural_key(username)
except UserModel.DoesNotExist:
# Run the default password hasher once to reduce the timing
# difference between an existing and a non-existing user (#20760).
UserModel().set_password(password)
else:
if user.check_password(password) and self.user_can_authenticate(user):
return user
def user_can_authenticate(self, user):
"""
Reject users with is_active=False. Custom user models that don't have
that attribute are allowed.
"""
is_active = getattr(user, 'is_active', None)
return is_active or is_active is None
至于使用Django内置身份验证视图的建议,它们对于自定义的非标准身份验证并不方便。您需要为您的用户类定义check\u密码
def check_password(self, raw_password):
if self.password == raw_password:
return True
else:
return False
因为如果检查django.contrib.auth.models下的源代码,
检查\u password()raise and NotImplemented error。Django 2.1身份验证对于任何身份验证都返回用户,前提是user.is\u active=TRUE,您需要先保存form.save(commit=False)的响应,然后设置自定义变量
if form.is_valid():
user= form.save(commit=False)
user.active=True
user.staff=False
user.admin=False
user.save()
messages.success(request, 'Account created successfully')
Django附带了一个登录视图。你应该用它,而不是自己写。请注意,Django 1.9已经过时,不再接受安全修复。升级至最新的1.11 LTS。请注意,用户注册时可能未正确设置密码。请尝试使用manage.py createsuperuser
创建一个超级用户,并查看您是否可以作为该用户登录。@Alasdair我已尝试使用我创建的超级用户登录。但它给出了一个不同的错误。@Alasdair使用django内置的登录名,我可以呈现到userlogin页面,但由于我的用户名没有为非超级用户填充,因此无法正确验证。设置user.set\u password(user.password)
看起来有误。您正在将密码设置为哈希值。我会试着去掉那条线。
if form.is_valid():
user= form.save(commit=False)
user.active=True
user.staff=False
user.admin=False
user.save()
messages.success(request, 'Account created successfully')