Modelform忽略required = True

时间:2014-10-04 10:40:11

标签: django django-forms

我有一个ModelForm用户可以用来更改他们的first_name,last_name和email。

我有一个干净的功能来检查用户是否正在尝试将电子邮件更改为已注册的电子邮件。

我的代码:

class DjangoUserForm(ModelForm):
    def __init__(self, *args, **kwargs):
        self.helper = FormHelper()
        self.helper.layout = Layout(
            Field('username', type="hidden"),
            Field('first_name'),
            Field('last_name'),
            Field('email'),
        )
        super(DjangoUserForm, self).__init__(*args, **kwargs)
        self.fields['first_name'].required = True
        self.fields['last_name'].required = True
        self.fields['email'].required = True

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


    def clean_email(self):
        email = self.cleaned_data['email']
        return email

    def clean(self):
        cleaned_data = super(DjangoUserForm, self).clean()

        email = self.cleaned_data['email']
        username = self.cleaned_data['username']

        if User.objects.exclude(username=username).filter(email=email).exists():
            if not self._errors.has_key('email'):
                from django.forms.util import ErrorList
                self._errors['email'] = ErrorList()
            self._errors['email'].append('Email is used by another user')


        return cleaned_data

该功能有效,但如果我尝试使用空的电子邮件字段保存表单,则会出现此错误:KeyError at /accounts/user/change/ 'email'。我有self.fields['email'].required = True,我期待django想出一个" required"错误。谁知道我做错了什么?

1 个答案:

答案 0 :(得分:1)

试试这个:

def clean(self):
    cleaned_data = super(DjangoUserForm, self).clean()
    if not self._errors:
        email = self.cleaned_data['email']
        username = self.cleaned_data['username']

        if not User.objects.exclude(username=username).filter(email=email).exists():
            return cleaned_data
        else:    
            from django.forms.util import ErrorList
            self._errors['email'] = ErrorList()
            self._errors['email'].append('Email is used by another user')