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 = []
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.
Here's the form code for instance:
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
Any help is appreciated!
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])
and
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!
You can explicitly define a field on the form. That way, you have full control over the field, including its validators:
class RegularUserForm(forms.ModelForm):
username = forms.CharField(max_length=30)
class Meta:
model = User
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With