django 保存方法不改变属性

django save method not changing attribute

正在尝试使用保存方法更改用户的管理员 =True。 但它并没有改变。

用户模型

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

还有我的 class 我想更改管理员的地方

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)

但是当将用户添加为管理员时,它不会将管理字段更改为 True。

您只保存了“经理”对象,没有保存“用户”对象。试试这个:

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)