from django.dispatch import receiver from django.db.models.signals import post_save, post_migrate from django.apps import apps from django.contrib.contenttypes.models import ContentType from django.contrib.auth.models import Permission from event.models import Event, EventGroup from guardian.shortcuts import assign_perm @receiver(post_save, sender=Event) def create_groups_for_event(sender, **kwargs): event, created = kwargs["instance"], kwargs["created"] if created: orgas = EventGroup.objects.create( name="{}_orgas".format(event.slug), event=event ) for perm in Permission.objects.filter( content_type=ContentType.objects.get_for_model(Event), codename__contains="event_"): assign_perm(perm.codename, orgas, event) EventGroup.objects.create( name="{}_participants".format(event.slug), event=event, ) @receiver(post_migrate) def create_event_permissions(sender, **kwargs): def event_specific_permissions(): opes = ['Add', 'Change', 'Delete'] models = [model.__name__.lower() for model in apps.get_models() if getattr(model, 'needs_event_permissions', False)] return [ ('event_{}_{}'.format(op.lower(), model), '{} {} for event'.format(op, model)) for op in opes for model in models ] content_type = ContentType.objects.get_for_model(Event) for (code, verbose) in event_specific_permissions(): Permission.objects.get_or_create( name=verbose, content_type=content_type, codename=code )