models.py 2.18 KB
from django.db import models

from django.db.models.signals import post_save
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from django.dispatch import receiver

# Create your models here.


class Organismo(models.Model):
    class Meta:
        verbose_name = 'Organismo'
        verbose_name_plural = 'Organismos'

    short_name = models.CharField(max_length=350, blank=False, verbose_name='Nombre del organismo')

    def __str__(self):
        return f'{self.short_name}'


class Dependencia(models.Model):
    objects = None

    class Meta:
        verbose_name = 'Dependencia'
        verbose_name_plural = 'Dependencias'

    organismo = models.ForeignKey('Organismo', on_delete=models.CASCADE)
    short_name = models.CharField(max_length=350, blank=False, verbose_name='Nombre de la dependencia')

    def __str__(self):
        return f'{self.organismo} - {self.short_name}'


def custom_permission_create(instance, model_class):
    content_type = ContentType.objects.get_for_model(model_class)
    action = 'view'
    codename = f'{action}_{instance.short_name.lower().replace(" ", "_")}'

    if not Permission.objects.filter(codename=codename, content_type=content_type).exists():
        Permission.objects.create(
            codename=codename,
            name=f'Can {action} {instance.short_name}',
            content_type=content_type,
        )


def custom_permission_delete(instance, model_class):
    content_type = ContentType.objects.get_for_model(model_class)
    action = 'view'
    codename = f'{action}_{instance.short_name.lower().replace(" ", "_")}'

    Permission.objects.filter(codename=codename, content_type=content_type).delete()


@receiver(post_save, sender=Dependencia)
@receiver(post_save, sender=Organismo)
def manage_permissions(sender, instance, created, **kwargs):
    model_class = type(instance)

    if created:
        custom_permission_create(instance, model_class)
    else:
        old_instance = model_class.objects.get(pk=instance.pk)
        if old_instance.short_name != instance.short_name:
            custom_permission_delete(old_instance, model_class)
            custom_permission_create(instance, model_class)