jjujuma
jjujuma

Reputation: 22785

How can I allow spaces in a Django username?

I'm trying to allow spaces in usernames in my Django app. This is from my form:

class SignUpForm(django.forms.ModelForm):
...
    username = django.forms.RegexField(
       regex=r'^[a-zA-Z]{1}[a-zA-Z -]{1,29}$'

I want username to start with a letter. After that I allow letters and spaces and hyphens. Somehow the form fails validation with "John Smith" and I have no idea why. Is there a restriction on spaces somewhere else?

Upvotes: 2

Views: 1765

Answers (1)

Jingo
Jingo

Reputation: 3230

the django auth user is based on an abstract user class (django.contrib.auth.models). Your bound form may be valid, but if you try to save the user object validation fails.

Have a look at the source from django.contrib.auth.models regarding the username:

class AbstractUser(AbstractBaseUser, PermissionsMixin):
    """
An abstract base class implementing a fully featured User model with
admin-compliant permissions.

Username, password and email are required. Other fields are optional.
"""
    username = models.CharField(_('username'), max_length=30, unique=True,
        help_text=_('Required. 30 characters or fewer. Letters, digits and '
                    '@/./+/-/_ only.'),
        validators=[
            validators.RegexValidator(r'^[\w.@+-]+$', _('Enter a valid username.'), 'invalid')
        ])

Hope this sheds some light on it.

Upvotes: 3

Related Questions