shahzaib
shahzaib

Reputation: 51

Overriding save method of User model with Abstract user in django

Django project with multiple two user types. I followed this tutorial to give two types of flags to the built in User model. When I try to login to django rest_framework_simple_jwt's login endpoint the response. Is there a problem in overriding save method.

{ "non_field_errors": [ "No active account found with the given credentials" ] }

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)

Upvotes: 4

Views: 3701

Answers (1)

slider
slider

Reputation: 12990

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

Upvotes: 1

Related Questions