Hello everyone I started working on a Django app for a class project but I am running into some confusion when trying to authenticate custom users.
The app is a social media platform for my school and as per the requirements of the project I must attach a biography and a role (position at the school). I figured the best way to do this is to attach it to the existing auth_user model but upon following almost all the content I could find users wont authenticate.
Even when supplied the correct information the user object is still None.
To start off lets take a look at my user model which is declared in an app called "landingpage"
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
bio=models.TextField()
role=models.CharField(max_length=32)
Then we go to the main app and declare which AUTH_USER_MODEL we want
AUTH_USER_MODEL = "landingpage.User"
Finally applying the migration commands
python manage.py makemigrations
python manage.py migrate
Then to test it out I have this code. My login system is a popup form so in order to avoid visiting the page I just redirect back to the index which also refreshes the page so I can update content based on the authenticated user. There is probably a better way to do this with javascript but I believe this is fine for now.
def login(request):
# If page is accessed via browser return because there is nothing here
if request.method=='GET':
return HttpResponseRedirect('/')
username=request.POST['username']
password=request.POST['password']
user = authenticate(username=username, password=password)
return HttpResponseRedirect('/')
Even when a correct username & password are supplied the user object will be None.
I suspect this might be because this is my 4th migration but I dont really understand the django framework that well because its only my third day.
I have read the docs here https://docs.djangoproject.com/en/4.2/topics/auth/customizing/#extending-the-existing-user-model
I also found a similar stackoverflow post but it didnt solve the issue Not able to authenticate custom user model in Django
Any help would be much appreciated!
You need to check values passed to backend in
request.POST, because authentication process is case-sensitive. Maybe they are lowercase, but username in DB is uppercase?When you've validated data but still can not login, you can change user password using
python manage.py changepasswordAfter you changed your password and
authenticatereturnsUserinstance - Your code is almost workingThe thing is,
authenticatejust verifies that user entered correct username+password, nothing more.So to actually login user, you need to use
loginfunction like this: