3

具有多种两种用户类型的 Django 项目。我按照本教程为内置的用户模型提供了两种类型的标志。当我尝试登录到 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)
4

1 回答 1

1

I think the problem is that your User isn't created when you're trying to create the Employee object. One approach could be to use the post_save signal like this:

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)

Basically, we want to create an Employee only after the user is saved (and has a pk) in the database.

More references: https://docs.djangoproject.com/en/2.0/ref/signals/#post-save

于 2018-06-13T17:43:46.897 回答