Hi! I wont to create a custom user registration, with the relative superuser section, to login with the email instead of the username.
I’ve wrote the following code, it’s seems work perfectly but when after the superuser registration, in the administration area I can’t be able to access.
it’s seems like no read the password, and gave me back the wrong password error message.
This is the code in the models.py file :
from django.db import models
from django.contrib.auth.models import (
AbstractBaseUser,
PermissionsMixin,
BaseUserManager,
)
# Create your models here.
class CustomAccountManager(BaseUserManager):
def create_superuser(self, buyer_email, buyer_name, password=None, **other_fields):
other_fields.setdefault('is_staff', True)
other_fields.setdefault('is_superuser', True)
other_fields.setdefault('is_active', True)
if other_fields.get('is_staff') is not True:
raise ValueError('Super must be assigned to is_staff=True')
if other_fields.get('is_superuser') is not True:
raise ValueError('Super must be assigned to is_superuser=True')
return self.create_buyer(buyer_email, buyer_name, password, **other_fields)
def create_buyer(
self, buyer_email, buyer_name, buyer_surname, password=None, **other_fields
):
if not buyer_email:
raise ValueError("Inserisci un indirizzo email valido!")
buyer_email = self.normalize_email(buyer_email)
buyer_user = self.model(
buyer_email=buyer_email,
buyer_name=buyer_name,
buyer_surname=buyer_surname,
**other_fields
)
if password:
password.set_password(password)
buyer_user.save(using=self.db)
return buyer_user
class Buyer(AbstractBaseUser, PermissionsMixin):
buyer_email = models.EmailField(unique=True, verbose_name="Indirizzo e-mail")
buyer_name = models.CharField(max_length=99, verbose_name="Nome")
buyer_surname = models.CharField(max_length=150, verbose_name="Cognome")
buyer_phone = models.CharField(max_length=99, verbose_name="Numero di cellulare")
buyer_registration_date = models.DateField(
auto_now_add=True, verbose_name="Data iscrizione"
)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=False)
objects = CustomAccountManager()
USERNAME_FIELD = "buyer_email"
REQUIRED_FIELDS = ["buyer_name"]
class Meta:
verbose_name = "Acquirente"
verbose_name_plural = "Acquirenti"
def __str__(self):
return self.buyer_name + " " + self.buyer_surname