Django custom model - field username gets removed

Hi I am writing a custom user model on django and i have username field along with email field when i set USERNAME_FIELD = 'username' i get this error django.core.exceptions.FieldDoesNotExist: User has no field named 'username' when i checked the migrations for the model i found that the username field did not exist among the model fields

i tried flushing and making migrations again but it still the same but when i change the field name to something other than username it works

here is my model:

from django.db import models

from django.contrib.auth.models import BaseUserManager, AbstractBaseUser
from django.db.models.enums import Choices
from django.utils.translation import gettext_lazy as _

class User(AbstractBaseUser):

class Role(models.TextChoices):
    User = 'USER', _('User')
    Admin = 'ADMIN', _('Admin')
    Stuff = 'STUFF', _('Stuff')

username        = models.CharField(max_length=64, unique=True)
email           = models.EmailField(max_length=256, unique= True, verbose_name="Email")
full_name       = models.CharField(max_length=256, verbose_name= "Full Name", null=True, blank=True)
active          = models.BooleanField(default=True, verbose_name= "Active")
role            = models.CharField(max_length=10, choices = Role.choices, default = Role.User, verbose_name= "Role")
created_at      = models.DateTimeField(auto_now_add=True)
modified_at     = models.DateTimeField(auto_now=True)

USERNAME_FIELD = 'username'
REQUIRED_FIELD = ['username', 'email','password']

def __str__(self):
    return self.username

def role(self):
    return self.role

def admin(self):
    return (self.role == self.Role.Admin)

def stuff(self):
    return (self.role == self.Role.Stuff)

def username(self):
    return self.username

Answers: 2

Answered by Ma Sao93, Oct. 22, 2021, 7:46 a.m.

Could you make sure this?

from django.contrib.auth.models import User


class UserAuth(models.Model):
      username = models.OneToOneField(User, on_delete = models.CASCADE, blank=True, null=True)
Answered by Ben Dover, Oct. 22, 2021, 10:50 a.m.

i actually got it to work by removing :

def username(self):
    return self.username

but i am not sure about the reason maybe becasue i used the property decorator

i would like to know the reason