所以我试着看看用户是否匹配他们的旧密码,如果他们不匹配,它会显示一条消息说"你的旧密码不正确"但是如果他们匹配旧密码,那么它应该检查用户是否正确匹配新密码和确认密码,如果他们不匹配,那么它应该给出一条消息说"你的新密码不匹配";但如果他们的密码是空的,它应该说"你的新密码是空的,但即使我的密码不是空的,它总是说我的密码是空的。我也尝试过if new_password1 or new_password2 == ''
,但也有相同的结果。
views.py
@login_required
def userchange(request):
if request.method == 'POST':
user = request.user
old_password = request.POST['Old password']
new_password1 = request.POST['New password1']
new_password2 = request.POST['New password2']
if user.check_password(old_password):
if new_password1 == new_password2:
if new_password1 or new_password2 is None:
return render(request, 'main/change.html', {'error':'Your new passwords are empty!'})
else:
user.set_password(new_password1)
return render(request, 'main/change.html', {'error':'Your password has been changed succesfully!'})
else:
return render(request, 'main/change.html', {'error':'Your new passwords do not match'})
else:
return render(request, 'main/change.html', {'error':'Your old password is incorrect'})
elif request.method == "GET":
return render(request, 'main/change.html')
change.html
<h1>Note: You will be logged out</h1>
<h2>{{ error }}</h2>
<form method="POST">
{% csrf_token %}
<input type="password" placeholder="Old password" name="Old password">
<input type="password" placeholder="New password" name="New password1">
<input type="password" placeholder="Confirm password" name="New password2">
<button type="submit">Change password</button>
</form>
你需要改变
if new_password1 or new_password2 is None:
if new_password1 is None or new_password2 is None:
如果new_password1
是任何真值…它将new_password1 or new_password2 is None
:求值为True or new_password2 is None
…这显然是真的……(你也可能是== ''
而不是is None
)