Search code examples
djangodjango-modelsdjango-rest-frameworkdjango-rest-auth

customize save function of rest-auth registration


I have a user model something like this

class Role(models.Model):

    ROLE_CHOICES = (
        ('agent', 'Agent'),
        ('agency', 'Agency'),
        ('manufacturer', 'Manufacturer'),
    )
    role = models.CharField(max_length=15, choices=ROLE_CHOICES)

    def __str__(self):
        return 'role'


class User(AbstractUser):

    role = models.ForeignKey(
        Role,
        on_delete=models.CASCADE,
        blank=True,
        null=True)

    def __str__(self):
        return str(self.id)

The user can be of 3 types. But at the time of registration, the user should be created with the role of agent.The endpoint for the user registration is /rest-auth/registration. This will create only a normal user with username and password. But i need to create the agent role as well. I believe, it should be done in save method of rest-auth registration serializer but I don't know how to customize the registration serializer. Can anyone shed me the light, please?


Solution

  • You can done it several ways.

    Method 1

    Use a callable default function on model:

    def get_defaul_role():
        role, created = Role.objects.get_or_create(role='agent')
        return role</b>
    
    class User(AbstractUser):
        role = models.ForeignKey(Role, on_delete=models.CASCADE, <b>default=get_defaul_role</b>)
    
        def __str__(self):
            return str(self.id)
    

    Method 2

    By overriding save() method

    class User(AbstractUser):
        role = models.ForeignKey(Role, on_delete=models.CASCADE, blank=True, null=True)
    
        def __str__(self):
            return str(self.id)
    
        def save(self, *args, **kwargs):
            if not self.pk: # If instance is created
                self.role, created = Role.objects.get_or_create(role='agent')
            return super().save(*args, **kwargs)
    

    Reference : Django's get_or_create()