如何在django中打印forms.ValidationError

时间:2018-06-11 14:05:33

标签: django forms

在教程中发现了这个,但“密码和confirm_password不匹配”不会打印到html页面。

from django import forms
from django.contrib.auth.models import User


class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
confirm_password = forms.CharField(widget=forms.PasswordInput())
first_name = forms.CharField(max_length=30)
last_name = forms.CharField(max_length=30)
email = forms.EmailField(max_length=254)

class Meta:
    model = User
    fields = ['username', 'first_name', 'last_name', 'email', 'password','confirm_password']

def clean(self):
    cleaned_data = super(UserForm, self).clean()
    password = cleaned_data.get("password")
    confirm_password = cleaned_data.get("confirm_password")

    if password != confirm_password:
        raise forms.ValidationError(
            "password and confirm_password does not match"
        )

更新: 在模板中使用{{form.non_field_errors}}进行了工作。

2 个答案:

答案 0 :(得分:1)

无论如何,您可以从您的视图,表单以及模型

中执行此操作
Class UserForm(forms.ModelForm):
pass

    def clean_password(self):
        data = self.cleaned_data
        password = self.cleaned_data.get('password')
        confirm_password = self.cleaned_data.get('confirm_password')

        if password != confirm_password:
            raise forms.ValidationError('Passwords must be same')

顺便说一句 如果使用Python 3.6然后是super()。method_name(args), 如果使用2.7然后是super(class_name,self).method_name(args)

答案 1 :(得分:0)

尝试:

def clean(self):
    cleaned_data = super(UserForm, self).clean()
    password = cleaned_data.get("password")
    confirm_password = cleaned_data.get("confirm_password")

    if password != confirm_password:
        raise forms.ValidationError(
            "password and confirm_password does not match"
        )
    else:
        form = UserForm()
        # If form is not valid, this would re-render 
        return render(request, 'template.html', {'form': form})