How to add max_length to allauth username

后端 未结 5 951
孤街浪徒
孤街浪徒 2021-01-25 07:08

I\'m using Django allauth as my user account framework for my django site. The docs show there is an ACCOUNT_USERNAME_MIN_LENGTH however there is no ACCOUNT_USERNAME_MAX_L

5条回答
  •  执笔经年
    2021-01-25 07:29

    This can be quickly done by extending DefaultAccountAdapter class and overriding the clean_username method. You need to also reference the clean_username once again after our custom validation to complete other inbuilt validations.

    It can be done as follows.

    from allauth.account.adapter import DefaultAccountAdapter
    from django.forms import ValidationError
    
    class UsernameMaxAdapter(DefaultAccountAdapter):
    
        def clean_username(self, username):
            if len(username) > 'Your Max Size':
                raise ValidationError('Please enter a username value less than the current one')
            return DefaultAccountAdapter.clean_username(self,username) # For other default validations.
    

    Finally, point to the subclass in your settings.py

    ACCOUNT_ADAPTER = 'YourProject.adapter.UsernameMaxAdapter'
    

    Reference: https://github.com/pennersr/django-allauth/blob/8fbbf8c1d32832d72de5ed1c7fd77600af57ea6f/allauth/account/adapter.py#L244

提交回复
热议问题