Reputation: 11814
I wanted to have case insensitive username for my project.
So i tried the following solution from https://simpleisbetterthancomplex.com/tutorial/2017/02/06/how-to-implement-case-insensitive-username.html
from django.contrib.auth.models import AbstractUser, UserManager
class CustomUserManager(UserManager):
def get_by_natural_key(self, username):
case_insensitive_username_field = '{}__iexact'.format(self.model.USERNAME_FIELD)
return self.get(**{case_insensitive_username_field: username})
class CustomUser(AbstractUser):
objects = CustomUserManager()
I have a signup form to create a user.
I have created a username called "test"
. It was saved properly in the database.
Then i tried to create another user name called "Test"
I found that form.save()
has saved "Test"
also into database. But i wanted that is should show some error that username already exists.
Then how is the solution which i am following is helping me.
Upvotes: 0
Views: 358
Reputation: 6144
Santosh from the same tutorial you have referred, it seems you need to take care of the registration process also. Only then the said solution will work.
The registration should also be case insensitive
Sample code found there
class CaseInsensitiveUserCreationForm(RegistrationFormUniqueEmail):
def clean(self):
username = self.cleaned_data.get(User.USERNAME_FIELD)
if username and User.objects.filter(username__iexact=username).exists():
self.add_error('username', 'A user with that username already exists.')
super(CaseInsensitiveUserCreationForm, self).clean()
Either this or may be you can convert the username to lower and save it. Does it help.
Upvotes: 1