gpt4 book ai didi

django - 覆盖 AbstractUser 模型的默认 django 用户名验证器

转载 作者:行者123 更新时间:2023-12-02 02:22:11 26 4
gpt4 key购买 nike

我正在使用 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

感谢任何帮助!

最佳答案

幸运的是,我找到了解决方案,我覆盖了表单中的验证器,但没有覆盖模型中的验证器(也做了相反的事情),所以我必须这样做:

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]

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

关于django - 覆盖 AbstractUser 模型的默认 django 用户名验证器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29921900/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com