Override default django username validators for AbstractUser model

后端 未结 2 1138
死守一世寂寞
死守一世寂寞 2021-01-19 22:59

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 fie

相关标签:
2条回答
  • 2021-01-19 23:39

    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
    
    0 讨论(0)
  • 2021-01-20 00:04

    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!

    0 讨论(0)
提交回复
热议问题