0

Django's default User model username validator allows testUser and TestUser for 2 different usernames.

I found a way to make username case insensitive during the registration but I am wondering if there's not a built-in way to do that.

Here is how I did it:

if form.is_valid():
    username = form.cleaned_data['username']

    brk = True

    try:
        User.objects.get(username__iexact=username)
    except:
        brk = False

    if brk:
        messages.warning(request, 'Username already in use')
        return redirect('signup')

    form.save()

This method looks a bit unprofessional. Isn't there a built-in way like there always is in Django? Something like an argument in the username model field.

mincom
  • 670
  • 5
  • 21
  • You can convert it first to a lowercase string using the string method string.lower() – aedry Mar 23 '19 at 19:46
  • But I want the username to be saved with the input font case in the database – mincom Mar 23 '19 at 19:48
  • 1
    https://stackoverflow.com/questions/13190758/django-case-insensitive-matching-of-username-from-auth-user – aedry Mar 23 '19 at 19:57

1 Answers1

0

I see two approaches to this:

1 - Create a constraint on the database, like this: Case insensitive unique model fields in Django?

2 - Override the validation on the form for the user name field. You would to use this for any or all form that deals with the username.

def clean_username(self):
    username = lower(self.cleaned_data['username')

    # You might even want to check with the username 
    #is already being used and raise a validation error here.

    return username
Stargazer
  • 1,442
  • 12
  • 19