我对 django 身份验证功能有问题



当我输入与数据库中相同的用户名和密码时,它显示"无效凭据"而不是"成功"。

def 登录(请求(: if request.method == 'POST':

username           = request.POST.get('user')
password1          = request.POST.get('password1')
a                  = authenticate( username=username, password=password1)
if a is not None:
return HttpResponse("Success")
else:
return HttpResponse("Invalid Credentials")
return render(request, 'login.html')

问题不在于身份验证本身,而在于创建用户。不能在数据库中使用原始密码创建用户。Django 将散列密码存储在数据库中。默认情况下,使用PBKDF2哈希器,尽管您可以对其进行配置。这意味着密码如下所示:

algorithm$iterations$salt$hash

身份验证模块将对您提供的密码进行哈希处理,并检查该密码是否匹配。

你可以使用createsuperuser管理命令 [Django-doc] 来创建一个超级用户:

django-admincreatesuperuser

或者您可以使用changepassword管理命令 [Django-doc] 更改用户的密码:

django-adminchangepasswordusername

对于普通用户,例如,您可以通过管理页面或使用 shell 中的.create_user(…)方法 [Django-doc] 进行:

$ python manage.py shell
Python 3.6.8 (default, Jan 14 2019, 11:02:34) 
[GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.contrib.auth import get_user_model
>>> get_user_model().objects.create_user(username='username', password='thepassword')
<User: username>

最新更新