覆盖AbstractUser模型

时间:2015-04-28 14:07:37

标签: django validation

我正在使用AbstractUser模型来创建自定义身份验证模型。

问题是我无法覆盖用户名字段的默认表单字段验证器,这是我到目前为止所尝试的内容:

class RegularUserForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
    super(RegularUserForm, self).__init__(*args, **kwargs)
    self.fields['username'].help_text = None
    self.fields['username'].default_validators = []
    self.fields['username'].validators = []

不确定如何执行此操作,覆盖help_text成功,我也尝试使用[None]代替[]self.fields['username'].validators = [validate_username],其中validate_username是我创建的自定义验证程序。

以下是表单代码:

class RegularUserForm(forms.ModelForm):
    username = forms.CharField(max_length=30, validators=[validate_username])
    email1 = forms.EmailField(required=True, label='')

class Meta:
    model = RegularUser
    fields = ['username', 'password', 'email', 'email1', 'gender', ]
    widgets = {'password': forms.PasswordInput(attrs={'placeholder': 'enter password'}),
               'email': forms.EmailInput(attrs={'placeholder': 'enter email'})
               }

def clean(self):
    cleaned_data = super(RegularUserForm, self).clean()
    email = self.cleaned_data.get('email')
    email1 = self.cleaned_data.get('email1')

    if email != email1:
        self.add_error("email1", 'emails do not match')
    return cleaned_data

感谢任何帮助!

2 个答案:

答案 0 :(得分:3)

谢天谢地,我找到了解决方案,我在表格中覆盖了验证器但不是模型中的验证器(也做了相反的反应)所以我不得不这样做:

from utils import validate_username
class RegularUserForm(forms.ModelForm):
    username = forms.CharField(max_length=50, validators=[validate_username])

class RegularUser(AbstractUser):
    def __init__(self, *args, **kwargs):
        super(RegularUser, self).__init__(*args, **kwargs)
        self._meta.get_field('username').validators = [validate_username]

读者注意:请确保覆盖模型和表单级验证器!

答案 1 :(得分:0)

您可以在表单上明确定义字段。这样,您就可以完全控制该字段,包括其验证程序:

class RegularUserForm(forms.ModelForm):
    username = forms.CharField(max_length=30)

    class Meta:
        model = User