Automatically assigning User token to custom profile model django rest framework

Viewed 176

I currently have a signal that automatically creates a Token object for a User when they sign up to the website.

I also have a custom User model, UserProfileInfo, in which I have a field that connects a Token to the User token = models.OneToOneField(Token,related_name='token',on_delete=models.CASCADE,blank=True,null=True) However, I want this to be automatically assigned when the userprofileinfo is created, which happens in a signal.

@receiver(post_save, sender=User)
def create_auth_token(sender, instance, created, **kwargs):
    if created:
        token = Token.objects.create(user=instance)
        UserProfileInfo

@receiver(post_save, sender=User)
def create_or_update_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfileInfo.objects.create(user=instance)
    else:
        instance.userprofileinfo.save()

(the first signal creates a token, the second creates the userprofileinfo)

I want to know how I can automatically assign a token to a user when the userprofileinfo is created.

1 Answers

You can have the code for both tasks within one signal method.

What you could do is, create your UserProfileInfo object first and then create a Token for the user.

@receiver(post_save, sender=User)
def create_or_update_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfileInfo.objects.create(user=instance)
        token = Token.objects.create(user=instance)
    else:
        instance.userprofileinfo.save()
Related