Search code examples
python-3.xdjangorequestabstractuser

How to access request.user with AbstractUser class


I am trying to create an order object and assign the order's customer field (which is a foreign key for User) to the current user. Even though it passes the if statement and it can authenticate the request.user, it assigns customer as a blank value.

When I print customer it prints a blank line, however when I print customer.id, it prints the ID of the customer. This happens in all views in the project so its a global issue

I belive this has something to do with the fact that my user class is inheriting from AbstractUser

utils.py

def cartData(request):
    if request.user.is_authenticated:
        print('This will print')
        customer = request.user
        print(customer) #This will print as a blank line
        print(customer.id) #This will print the request.user.id
        print(customer.username) #This will print the request.user.username
        order, created = Order.objects.get_or_create(customer=customer, complete=False)

models.py

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

class User(AbstractUser):
   author = models.BooleanField(default=False)

settings.py

AUTH_USER_MODEL = 'main.User' 

The database is updated with the user as blank too. I feel like this may be an easy one but I can't figure it out! Thanks.


Solution

  • I have now added first_name and last_name to the user and it works. Still a little confused though as I did not set __str__ or __repr__ to first or last name on the user model. If anyone knows why this is the case I would be interested to know. Thanks for al the help!