iTayb
iTayb

Reputation: 12743

Modify django's username policy?

Django default admin authentication module disallows use of the \ char in usernames. How can I make it accept it?

It looks like it's possible to edit contrib/auth/models.py's username field's validator, but that won't do because it requires a change to django's base code.

Upvotes: 1

Views: 2845

Answers (2)

Ian Price
Ian Price

Reputation: 7616

You can use custom regex validators and a custom user model in order to achieve this. Be sure to set USERNAME_FIELD and REQUIRED_FIELDS in your model definition and AUTH_USER_MODEL in your settings.

custom_userprofile_app.models.py

from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin

class User(AbstractBaseUser, PermissionsMixin):
    username = models.CharField(_('username'), max_length=30, unique=True,
                                help_text=_('Required. 30 characters or fewer.'),
                                validators=[
                                    validators.RegexValidator(r'^(.*)$',
                                                              _('Enter a valid username. '
                                                                'This value may contain any characters', 'invalid'),
                                    validators.MinLengthValidator(5, 'Username must be at least 5 characters'),
                                ],
                                error_messages={
                                    'unique': _("A user with that username already exists."),
                                })
    # The rest of your fields, etc
    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email','first_name','last_name']

settings.py

AUTH_USER_MODEL = 'custom_userprofile_app.User'

Upvotes: 3

v1k45
v1k45

Reputation: 8250

You can override django's default User model and then edit the regex validator. You are just required to create a child class of base user model and then define a setting for that.

Read how to specify custom user model @ django docs

Upvotes: 0

Related Questions