Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override default django username validators for AbstractUser model

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!

like image 706
HassenPy Avatar asked Apr 28 '15 14:04

HassenPy


2 Answers

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!

like image 179
HassenPy Avatar answered Oct 29 '22 17:10

HassenPy


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
like image 22
knbk Avatar answered Oct 29 '22 18:10

knbk