问题描述
我正在使用AbstractUser模型创建自定义身份验证模型。
I am using the AbstractUser model to create a custom auth model.
问题是我无法覆盖用户名字段的默认表单字段验证器,这是我到目前为止已经尝试过的方法:
The problem is that i was unable to override the default form field validators for the username field, here's what i have tried so far:
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是成功的,我也尝试使用 [无]
代替 []
和 self.fields ['username']。validators = [validate_username]
其中validate_username是我创建的自定义验证器。
Not sure how to do this, overriding the help_text was successful, i also tried using [None]
instead of []
and self.fields['username'].validators = [validate_username]
where validate_username is a custom validator that i created.
例如,这是表单代码:
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
感谢您的帮助!
推荐答案
很高兴我找到了解决方案,我在重写验证器。形式,但不是模型中的形式(也相反),所以我必须这样做:
Thankfully i found the solution, i was overriding the validators in the forms but not the ones in the models (also did the opposite) so i had to do this:
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]
给读者的提示:确保同时覆盖了模型和形式级验证者!
Note for readers: make sure you override both model and form level validators!
这篇关于覆盖AbstractUser模型的默认Django用户名验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!