from django.utils import timezone
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager
class UserManager(BaseUserManager):
def create_user(self, email, password, username=None):
user = self.model(email=self.normalize_email(email))
user.set_password(password)
user.created_at = timezone.now()
user.save()
return user
def create_superuser(self, username, email, password):
user = self.model(email=self.normalize_email(email))
user.set_password(password)
user.is_staff = True
user.is_active = True
user.is_superuser = True
user.save()
return user
class Role(models.Model):
name = models.CharField(max_length=100, unique=True, blank=True, null=True)
slug = models.SlugField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True, verbose_name="Created at")
updated_at = models.DateTimeField(auto_now=True, verbose_name="Updated at")
class Meta:
verbose_name = "Role"
verbose_name_plural = "Roles"
ordering = ["name"]
db_table = "user_roles"
def __str__(self):
return self.name
def get_absolute_url(self):
return f"{self.slug}"
class User(AbstractBaseUser, PermissionsMixin):
objects = UserManager()
role = models.ForeignKey(Role, on_delete=models.SET_DEFAULT, default=1, null=True, blank=True)
username = models.CharField(max_length=100, unique=True, blank=True, null=True)
email = models.EmailField(max_length=255, unique=True)
is_active = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
email_verified_at = models.DateTimeField(auto_now=False, null=True, blank=True)
confirmed = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True, verbose_name="Created at")
updated_at = models.DateTimeField(auto_now=True, verbose_name="Updated at")
class Meta:
verbose_name = "User"
verbose_name_plural = "Users"
ordering = ["username"]
db_table = "users"
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
I get the following error and would like to understand why is the foreign key constraint failing pls
django.db.utils.IntegrityError: (1452, ‘Cannot add or update a child row: a foreign key constraint fails (play
.users
, CONSTRAINT users_role_id_1900a745_fk_user_roles_id
FOREIGN KEY (role_id
) REFERENCES user_roles
(id
))’)