0

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?

Jason
  • 72
  • 7

3 Answers3

0

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.

Javier Aguila
  • 574
  • 4
  • 5
  • Thanks for your reply. This gets me a little further, but I think I may have hit a bug in allauth. If I set my account_username_validator to be just like what you have up there (formatted for my code of course), I get an error saying account_username_validator is expected to be a list. If I make it a list, I get an assert error because that check isn't looking for only strings. – Jason Mar 30 '17 at 00:57
  • Oh! I see it. Good find! It supposed is has been fixed but I imagine that it hasn't been deployed. You also can define you own custom user model and use the attribute validators of CharField. – Javier Aguila Mar 30 '17 at 06:35
0

I found that I was actually hitting a bug in the software.

https://github.com/pennersr/django-allauth/pull/1648

For anyone else that happens by.

Jason
  • 72
  • 7
0

With reference to Javier's Fix, your validators file should look like this:

import re
from django.utils.deconstruct import deconstructible
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ValidationError

@deconstructible
class CustomUsernameValidator(object):
    message = _('Invalid username')

    def __call__(self, value):
        if not re.match(r'[a-zA-Z0-9_@#-]+', value):
            raise ValidationError(self.message, code='invalid_username')


custom_usename_validator = [CustomUsernameValidator()]

And your settings.py file:

ACCOUNT_USERNAME_VALIDATORS = 'mypath.to.validators.custom_usename_validator'
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Abdul Wahab
  • 27
  • 1
  • 4