models.py
2.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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)