我这里有一个奇怪的问题。当我登录时,它按预期运行良好,但是当我尝试注销并再次尝试登录时,它说我的密码无效。
我检查了我的 User 表,每次我使用 authenticate() 函数时它都在更改我的密码。
我在一个月前遇到了这个错误(当时还是 django 1.8),但在经过多次测试、跟踪和祈祷之后,我完全不知道发生了什么。不过它只发生在我的本地机器上。
authentication.py
在 authenticate() 函数之后,我的密码已经更改(试图在该函数之后放置一个断点,所以我确定这是罪魁祸首)。
from django.contrib.auth import authenticate, logout, login
def signin(request):
if request.method == "POST":
result = {}
data = req_data(request)
try:
user = authenticate(username = data['email'], password = data['password'])
if user:
if user.is_active:
login(request, user)
#return success for redirection
else:
raise ValueError("This user is inactive. Please contact your admin.")
else:
raise ValueError("Invalid username/password.")
except Exception as e:
return HttpResponse(e, status = 400)
else:
return redirect("login")
def signout(request):
logout(request)
return redirect("login")
#gets the params from ajax post
def req_data(request):
return json.loads(request.body.decode("utf-8")) if request.body.decode("utf-8") else {}
我检查了数据库并得到了这个结果。
旧密码
pbkdf2_sha256$20000$N4esMaOT5BYi$nIehHw63b+iZSz2Vmu1hEO10BqPfzAGu1cZA1ci/nXI=
新密码(登录后)
pbkdf2_sha256$24000$KVZeuG4pgSkv$VIenbuq0Wk8sYZros4kE4Q7W0Jt+bOC23ha4/VSOXV8=
编辑:
与此同时,我没有使用 authenticate() 而只是使用通用密码。
username = data.get('email',"")
password = data.get('password',"")
if password == "genericpassword123":
try:
user = User.objects.get(email = username)
user.backend = 'django.contrib.auth.backends.ModelBackend'
except User.DoesNotExist:
raise ValueError("Invalid username/password.")
else:
user = authenticate(username = username, password = password)
if user:
if user.is_active:
login(request, user)
#return success for redirection
else:
raise ValueError("This user is inactive. Please contact your admin.")
else:
raise ValueError("Invalid username/password.")
python 2.7
Django 1.9
Postgres 9.4
谢谢!
最佳答案
它现在正在工作。我从没想过它可以在不同的帐户中使用不同的密码。
关于python - Django authenticate() 重置密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40508198/