Enable a signal only for google log in

I have a customer panel in which customer can sign up by filling a user creation form or via sign in with google. To enable the user to sign in with google I have created a signal as following:

@receiver(post_save, sender = CustomUser)
    def customer_create(sender, instance, created, *args, **kwargs):
        if created:
            instance.is_customer = True
            instance.save()
            customer = Customer.objects.create(user=instance)
            customer.username = instance.username
            customer.email = instance.email
            customer.first_name = instance.first_name
            customer.last_name = instance.last_name
            customer.save()

it works fine for the user who are signed with via google. But when user tries to sign up via form a duplicate key value violation arises as it also works with the signal.

How can I enable the signal only for the users who are signed in via google?

Signal is going to execute for every post_save action that may happen for the CustomUser model. So, you cannot make it conditional only for the users that are signed in via google.

If you really want to do it this way, assuming you know how a user signed up in your platform, you could do something like this:

if instance.signup_method === "google":
   return

if created:
   instance.is_customer = True
   instance.save()
   ...

Though, you could also consider overriding the save method of the CustomUser model.

Back to Top