django:SetPasswordForm没有错误无效

时间:2017-02-18 09:31:18

标签: python django forms web passwords

这是我第一次使用SetPasswordForm。表单无效但未显示错误消息。所以我很难弄清哪个部分出了问题。

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'),

当用户输入新密码并且操作成功时,页面将重定向到password_change_done。

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/profile.html', {'error_message': 'password mismatch'})
        else:
        return render(request, 'blog/profile.html', {'error_messages': form.errors })
    else:
        return redirect(reverse('blog:profile', args=[form.user.get_username()]))


@login_required
def password_change_done(request):
return render(request, 'blog/password_change_done.html')

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 __init__(self, user, data, **kwargs):
        self.user = user
        super(PasswordChangeForm, self).__init__(data, **kwargs)
    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

templates.py

{{ form.errors }}
{{ form.non_field_errors }}
{% if error_message %}
    <h2><strong>{{ error_message }}</strong></h2>
{% else %}<br>
{% endif %}
<form class="form-horizontal" role="form" action="{% url 'blog:password_change' user.username %}" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit" class="button-primary">submit</button></div>
</form>

我放了{{form.errors}}和{{form.non_field_errors}}所以如果错误发生,它可以在网站上显示错误消息。但是到目前为止,只要用户点击提交按钮,就不会显示任何消息,似乎没有任何反应。

1 个答案:

答案 0 :(得分:0)

这里有很多问题,但主要问题 - 正如我之前告诉过的那样 - 是你如何将事情传递给模板。您需要按照文档中所示的模式进行操作,并且需要一致关于变量命名。

首先,将密码检查移至表单本身:

class PasswordChangeForm(SetPasswordForm):
    ...
    def clean(self):
        password1 = self.cleaned_data.get('password1')
        password2 = self.cleaned_data.get('password2')
        if password1 1= password2:
            raise forms.ValidationError('password mismatch')

现在,修复您的观点:

def password_change(request, username):
    if request.method == 'POST':
        form = PasswordChangeForm(data=request.POST, user=request.user)
        if form.is_valid():
            update_session_auth_hash(request, form.username)
            form.save()
            return HttpResponseRedirect('/blog/password_change_done/') 
        else:
            return render(request, 'blog/profile.html', {'form': form })
    else:
        return redirect(reverse('blog:profile', args=[username]))

最后,从模板中删除{{ error_messages }}