CustomUser model setup in django rest framework

i tried creating a CustomUser model which inherits from AbstractBaseUser in drf, but when i try creating a new super user to log into the admin site, it doesn't work. it shows superuser created successfully but when running manage.py shell and trying to get that exact user i just created, it apparently doesn't exist.

my custom user model:

from django.db import models
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, Group, Permission
from .managers import UserManager
from django.utils.translation import gettext_lazy as lz

import uuid
import base64

ITEM = (
    ("pastries", 'pastries'),
    ("rentals",'rentals'),
    ("music", 'music'),
    ("help", 'help')
)
class CustomUser(AbstractBaseUser, PermissionsMixin):
    objects = UserManager()
    id = models.CharField(max_length=12, unique=True, primary_key=True, editable=False)
    username = models.CharField(max_length=55, unique=True)
    email = models.EmailField(verbose_name=lz('email address'), unique=True, max_length=255)
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    is_staff = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    is_superuser = models.BooleanField(default=False)
    last_login = models.DateTimeField(null=True, blank=True)
    is_verified = models.BooleanField(default=False)
    date_joined = models.DateTimeField(auto_now_add=True)
    
    groups = models.ManyToManyField(
        Group,
        related_name='accounts_user_groups',
        blank=True,
        help_text="the groups this user belongs to",
        verbose_name=lz('groups')
    )
    
    user_permissions = models.ManyToManyField(
        Permission,
        related_name='accounts_user_permissions',
        blank=True,
        help_text="permissions for this user",
        verbose_name=lz('user permissions')
    )
    
    USERNAME_FIELD = "email"
    REQUIRED_FIELDS = ["username"]
    
    
    def __str__(self) -> str:
        return self.email
    
    @property
    def get_full_name(self):
        return f'{self.first_name} {self.last_name}'
    
    def save(self, *args, **kwargs):
        if not self.id:
            # Generate a shorter base64-encoded UUID
            hex_string = uuid.uuid4().hex
            bytes_data = bytes.fromhex(hex_string)
            data = base64.urlsafe_b64encode(bytes_data).decode('ascii')[:12]
            self.id = data.replace("-","").replace("_", "")
        
        super().save(*args, **kwargs)

my managers.py file

from django.contrib.auth.models import BaseUserManager
from typing import Any
from django.core.validators import validate_email
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as lz

class UserManager(BaseUserManager):
    def email_validator(self, email):
        try:
            validate_email(email)
        except ValidationError:
            raise ValueError(lz("enter a valid email address"))
        
        
    def create_user(self, email, username, password, **extra_fields):
        if email:
            email = self.normalize_email(email)
            self.email_validator(email)
        else:
            raise ValidationError(lz("an email address is required"))
        
        if not username:
            raise ValidationError(lz("a username is required"))
            
        user = self.model(self, email, username, password, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user
    
    
    def create_superuser(self, email, username, password, **extra_fields):
        extra_fields.setdefault("is_staff", True)
        extra_fields.setdefault("is_superuser", True)

        if extra_fields.get("is_staff") is not True:
            raise ValueError(lz("is staff must be true for admin user"))
        if extra_fields.get("is_superuser") is not True:
            raise ValueError(lz("is superuser must be true for admin user"))
        
        user = self.create_user(email, username, password, **extra_fields)
        user.save(using=self._db)
        return user

followed all the resources i saw on the drf docs, still no solution by default, is_staff and is_superuser is set to true, but still, it can't be found, or rather, is not created...

Try this in your create _ user remove 'self' from model instantiation

user = self.model(
email=email,
username=username,
**extra_fields`enter code here`
)
user.set_password(password)
user.save(using=self._db)
return user

then delete your migrations python manage.py makemigrations python manage.py migrate python manage.py createsuperuser hope this helps

Вернуться на верх