Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django case insensitive login, mixed case username

Tags:

django

I'm trying to do case insensitive login for a Django app, without altering original username case. According to my research, the best approach is to create a related field to store the username in lowercase at registration. No reinventing the user model, it's a simple solution, right? My dilemma: How to do you take data from one model, change it, and save it in another model when the object is created?

Here is what is in models.py:

from django.db import models
from django.contrib.auth.models import User

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    lc_n = User.username
    lc_n = lc_n.lower()
    lowercase_name = models.CharField(max_length=30, default=lc_n)

When running python manage.py makemigrations there is the following error:

AttributeError: type object 'User' has no attribute 'username'

User does have that attribute, but it can't be accessed this way.

Please forgive me, as this must contain some simple fundamental flaw. Any support that may be offered will be greatly appreciated.

like image 918
codingcoding Avatar asked Dec 26 '22 00:12

codingcoding


1 Answers

You don't need any additional models to implement case insensitive login. Django supports case insensitive filtering by iexact operator:

user = User.objects.get(username__iexact=name)
like image 134
catavaran Avatar answered Jan 08 '23 09:01

catavaran