Case insensitive username in Django signup form

Viewed 2118

Here is my signup form,

class SignupForm(forms.ModelForm):

   class Meta:
       model = User
       fields = ['first_name', 'last_name','username', 'email', 'password']

    def clean_username(self):
        username = self.cleaned_data.get('username')
        email = self.cleaned_data.get('email')

        if username and User.objects.filter(username=username).exclude(email=email).count():
            raise forms.ValidationError('This username has already been taken!')
       return username

This works well to check if there is same username presents or not. However it does not check for case insensitivity. If there is a username e.g. 'userone', then it also accepts a username with 'Userone'. Although it does not break any functionality, but looks very unprofessional.

My question is how can I check for case insensitive right in the forms, and raise error?

3 Answers

Sometimes I faced the same issue. Django considers username unique different in lower or upper case. Like if I enter John, it a unique username and if I enter john, it's a new username. I need to consider John and john not in the database. As simple as facebook do, both uppercase and lower case username name is same, unique.

So I achieve this just changing my signup code like this.

username = self.cleaned_data.get('username').lower()

Also, in my login code, I convert my username to lower. So that, all time it saves username lower in the database and log in with lower case username. Although a user tries to login with upper case username, then it saves to the database by converting to lower case.

You can use __iexact here:

User.objects.filter(username__iexact=username).exclude(email=email).exists()  # instead of count, used exists() which does not make any DB query

Simplest method I think is:

Use .exists() method, if true then validation error else return ❤

Related