Override default django username validators for AbstractUser model

后端 未结 2 1139
死守一世寂寞
死守一世寂寞 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-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!

提交回复
热议问题