用django中的Abstract用户覆盖User模型的保存方法

时间:2018-06-13 09:05:29

标签: django python-3.x django-models django-rest-framework django-rest-framework-jwt

Django项目有多个两种用户类型。我按照这个tutorial给内置的User模型提供了两种类型的标志。当我尝试登录django rest_framework_simple_jwt的登录端点时的响应。覆盖保存方法是否存在问题。

  

{       “non_field_errors”:[           “找不到具有给定凭据的活动帐户”       ]}

class User(AbstractUser):
    email = models.EmailField(unique=False,)
    first_name = models.CharField(max_length=30, blank=True)
    last_name = models.CharField(max_length=30, blank=True)
    date_joined = models.DateTimeField(auto_now_add=True)
    is_active = models.BooleanField(default=True)
    is_employee=models.BooleanField(default=False)
    is_manager=models.BooleanField(default=False)

    def save(self,*args,**kwargs):
        if self.is_employee:
                Employee.objects.create(manager=self)
        super(User,self).save(*args,**kwargs)

1 个答案:

答案 0 :(得分:1)

我认为问题在于,当您尝试创建User对象时,未创建Employee。一种方法可能是使用post_save信号,如下所示:

from django.db import models
from django.dispatch import receiver

class User(AbstractUser):
    email = models.EmailField(unique=False,)        
    # ...other fields
    # and don't override save()

@receiver(models.signals.post_save, sender=User)
def user_created(sender, instance, created, **kwargs):
    if created and instance.is_employee:
        Employee.objects.create(manager=instance)

基本上,我们只想在数据库中保存用户(并且有一个Employee)之后才创建pk

更多参考资料:https://docs.djangoproject.com/en/2.0/ref/signals/#post-save