Trying to use the save method to change the admin =True, on a user. But it is not changing.
User models
class User(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
first_name = models.CharField(max_length=55, null=True, blank=True)
last_name = models.CharField(max_length=55, null=True, blank=True)
phone_number = models.CharField(max_length=12, null=True, blank=True)
delivery_info = models.ManyToManyField(Address, related_name='address_info', blank=True)
is_active = models.BooleanField(default=True)
verified = models.BooleanField(default=False)
staff = models.BooleanField(default=False) # a admin user; non super-user
admin = models.BooleanField(default=False) # a superuser
And my class where i want to change the admin
class Employee(models.Model):
"""
Main class containing the employee
"""
user = models.OneToOneField(User, related_name='employee', on_delete=CASCADE)
# Every employee have to have an ID, that is unique
slug = models.SlugField(max_length=255, unique=True, blank=True)
date_joined = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.user.email
# Using slug to id the employee and be able to have its own
# profile page to change information
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.user)
super(Employee, self).save(*args, **kwargs)
class Manager(models.Model):
"""
Holding the manager/admin employee
"""
manager = models.ForeignKey(Employee, related_name='manager', on_delete=CASCADE)
def __str__(self):
return self.manager.user.email
def save(self, *args, **kwargs):
if self.manager:
self.manager.user.admin = True
self.manager.user.staff = True
super(Manager, self).save(*args, **kwargs)
But when adding user as a manager, it does not change the admin fields to True.
CodePudding user response:
You are saving only the "Manager" object, not the "User" one. Try this:
def save(self, *args, **kwargs):
if self.manager:
user = self.manager.user
user.admin = True
user.staff = True
user.save()
super(Manager, self).save(*args, **kwargs)