3

I am working on a website that requires user username to include forward slash. something like 'CSC/15U/1155' as username.

django says 'Enter a valid username. This value may contain only letters, numbers, and @/./+/-/_ characters.'.

my question is as follows: is there a way to allow forward slash in username without extending the user model, if there is please help.

thanks in advance.

AIbrahim
  • 41
  • 5
  • Hi, just trying to help. Official docs says you [should subclass `User`](https://docs.djangoproject.com/en/2.1/ref/contrib/auth/#django.contrib.auth.models.User.username_validator) with a `Meta CustomUser`. – dani herrera Nov 17 '18 at 18:37

1 Answers1

2

This error is occurring because of Django's Username validator. So you can override it like this(Copy Pasted from documentation):

from django.contrib.auth.models import User
from django.contrib.auth.validators import ASCIIUsernameValidator

class CustomUser(User):
    username_validator = ASCIIUsernameValidator()  # or your custom validator

    class Meta:
        proxy = True  # If no new field is added.

Or if you don't want to use any validators, then just override the username field.

Update

When you are using CustomUser model, you need to update AUTH_USER_MODEL in settings.py. For example:

#  settings.py

AUTH_USER_MODEL = 'yourapp.models.CustomUser'

And if you want to override the username field in CustomUser, then you can do it like this:

 from django.contrib.auth.models import AbstractUser


 class CustomUser(AbstractUser):
      username = models.CharField(max_length=255, unique=True)

Please see the documentation on how to use custom User model in Django.

For adminsite, you need to override your login form. For example:

# some form

from django.contrib.auth.forms import AuthenticationForm

class LoginForm(AuthenticationForm):
    username = forms.CharField(label='username', max_length=100)

And update in urls.py(as per this answer):

from django.contrib import admin
from my.forms import AuthenticationForm

admin.autodiscover()
admin.site.login_form = LoginForm

Default adminsite login does not work because it uses Username field which normalizes the input value.

ruddra
  • 50,746
  • 7
  • 78
  • 101
  • Thanks for the reply but i still cannot create username containing forward slash. i think **ASCIIUsernameValidator** is only allowing letters, numbers, and @/./+/-/_ characters.'. in my case i wants to allow forward slash '/' – AIbrahim Nov 17 '18 at 19:02
  • In that case, just override the username field like the documentation mentioned in the answer. – ruddra Nov 17 '18 at 19:02
  • I overrides the username the validator now it works in the shell with User.objects.create_user() but unfortunately it does not work with django admin form – AIbrahim Nov 17 '18 at 19:30