我正在使用密码更改表单,其中包含旧密码,新密码和确认新密码。如果旧密码与当前用户的密码不匹配,则显示错误消息。此外,如果新密码和密码确认彼此不匹配,则会显示错误消息。到目前为止,我一直收到错误消息,我想知道哪个部分出了问题。为什么没有返回?
错误消息
ValueError at /blog/password_change/blue/
The view blog.views.password_change didn't return an HttpResponse object. It returned None instead.
urls.py
url(r'^password_change/(?P<username>[-\w.]+)/$', views.password_change, name='password_change'),
url(r'^password_change_done/$', views.password_change_done, name='password_change_done'),
forms.py
class PasswordChangeForm(SetPasswordForm):
error_messages = dict(SetPasswordForm.error_messages, **{
'password_incorrect': ("Your old password was entered incorrectly. Please enter it again."),
})
oldpassword = forms.CharField(
label=("Old password"),
strip=False,
widget=forms.PasswordInput(attrs={'autofocus': True}),
)
field_order = ['oldpassword', 'password1', 'password2']
def clean_oldpassword(self):
oldpassword = self.cleaned_data["oldpassword"]
if not self.user.check_password(oldpassword):
raise forms.ValidationError(
self.error_messages['password_incorrect'],
code='password_incorrect',
)
return oldpassword
views.py
@login_required
def password_change(request, username):
if request.method == 'POST':
form = PasswordChangeForm(data=request.POST, user=request.user)
if form.is_valid():
oldpassword = form.cleaned_data.get('oldpassword')
password1 = form.cleaned_data.get('password1')
password2 = form.cleaned_data.get('password2')
if password1 == password2:
update_session_auth_hash(request, form.username)
form.save()
return HttpResponseRedirect('/blog/password_change_done/')
else:
return render(request, 'blog/detail.html', {'error_message': 'password mismatch'})
else:
form = PasswordChangeForm(user=request.user)
return redirect(reverse('blog:profile', args=[form.user.get_username()]))
答案 0 :(得分:0)
将您的观点更改为以下代码
@login_required
def password_change(request, username):
if request.method == 'POST':
form = PasswordChangeForm(data=request.POST, user=request.user)
if form.is_valid():
oldpassword = form.cleaned_data.get('oldpassword')
password1 = form.cleaned_data.get('password1')
password2 = form.cleaned_data.get('password2')
if password1 == password2:
update_session_auth_hash(request, form.username)
form.save()
return HttpResponseRedirect('/blog/password_change_done/')
else:
return render(request, 'blog/detail.html', {'error_message': 'password mismatch'})
else:
return render(request, 'blog/detail.html', {'error_messages': form.errors })
else:
form = PasswordChangeForm(user=request.user)
return redirect(reverse('blog:profile', args=[form.user.get_username()]))
答案 1 :(得分:0)
首先,你有重定向并以错误的方式呈现;你应该重定向成功,并在失败时渲染。
你的实际问题是由于错误的缩进造成的;如果请求是POST但表单无效,则没有return语句。你应该取消最后一行 - 这应该是渲染 - 以便这个案例击中那一行。