How can i prevent duplicate signals? am having a user being assigned to both 'client' and 'worker' instead of one group respectively

What could i be doing wrong, the code is executing two times. instead of loading the user to his specific group from django.db.models.signals import post_save

from django.contrib.auth.models import User
from django.contrib.auth.models import Group


from .models import Client, Worker


def client_profile(sender, instance, created, **kwargs):
    if created:
        group = Group.objects.get(name='client')
        instance.groups.add(group)
        Client.objects.create(
            user=instance,
            name=instance.username,
        )
        print('Profile created!')


post_save.connect(client_profile, sender=User, dispatch_uid="client_profile")


def worker_profile(sender, instance, created, **kwargs):
    if created:
        group = Group.objects.get(name='worker')
        instance.groups.add(group)
        Worker.objects.create(
            user=instance,
            name=instance.username,
        )
        print('Profile created!')


post_save.connect(worker_profile, sender=User, dispatch_uid="worker_profile")

It is the expected behaviour, you are telling your signals that each time a User model is created you should add them to a group with no specific instruction.

What you could do instead is checking if a user is already in a given group, if yes do not add them, else add to the group.

Signals in Django

Also I can see that you have two different models one for the worker one for the client, so the best workaround would be to have the sender as either your worker or the client model and then adding the instance of the user to the group.

Back to Top