Home > Software engineering >  Django creating multiple groups with post_save
Django creating multiple groups with post_save

Time:08-07

I need to auto-create several groups with a post_save signal. I almost have this working however, as a novice, I can't get the syntax right. When I use the code below, instead of two groups, I get one group with the name ('manager', 'employee').

How would I change this to add two groups - manager and employee?

# autocreate basic employee groups when new company is created
@receiver(post_save, sender=Tenant)
def create_basic_group(sender, created, **kwargs):
    if created:
        # Get or create group
        new_group, created = Group.objects.get_or_create(
            name=('manager', 'employee'))

CodePudding user response:

Currently, get_or_create fn is taking name as string ('manager', 'employee')

You should create the groups in for loop like:

# autocreate basic employee groups when new company is created
@receiver(post_save, sender=Tenant)
def create_basic_group(sender, created, **kwargs):
    if created:
        groups_to_check = ["manager", "employee"]
        for group_name in groups_to_check:
            Group.objects.get_or_create(name=group_name)

  • Related