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)
答案 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