djangodjango-1.10

Trying to override Django User model username validation


I am trying to override the django default User model username field to allow hashtags in usernames.

I know the model itself will let me do this but the standard form registration doesn't seem to allow it. I'm using django-allauth as well.

How do I replace the regex in the default User model form to allow a hashtag in the username?


Solution

  • django-allauth has a lot of configuration, one of its options is set the validators for username

    ACCOUNT_USERNAME_VALIDATORS
    

    for a better reference you can check https://django-allauth.readthedocs.io/en/latest/configuration.html

    The ACCOUNT_USERNAME_VALIDATORS accept a list of paths of custom username validators. So, you can define something like:

    ACCOUNT_USERNAME_VALIDATORS = ('myproject.myapp.validators.custom_username_validators')
    

    and in the specified path 'myproject.myapp.validators.CustomUsernameValidtor' you must define a validator class like:

    import re
    from django.utils.deconstruct import deconstructible
    from django.utils.translation import ugettext_lazy as _
    
    @deconstructible
    class CustomUsernameValidator(object):
        message = _('Invalid username')
    
        def __call__(self, value):
            if not re.match(r'[a-zA-Z0-9_@#-]+', value)
                raise DjangoValidationError(self.message, code='invalid_username')
    

    Hope this can help you.

    Regards.