How to set permissions for a group automatically?

Viewed 46

When creating the Django model, Django will automatically create permissions for CRUD operations. Provided that user groups have been created earlier, the question arises: how to add the necessary permissions for a group automatically?

At the moment, I create data migrations in which I add the necessary permissions for the group "manually". Maybe there is a way to do this without data migration?

1 Answers

You can create a Signal for that purpose in which you can assign permissions to the group.

@receiver(models.signals.post_save, sender=User)
def assign_permission_signal_handler(sender, instance, created, **kwargs):
    if created:
       group = Group.objects.get(name='Group name')
       instance.groups.add(group)
       group.permissions.set('permission')
       instance.save()
Related