from django.db import models from django.contrib.auth.models import User, Group, Permission from django.contrib.contenttypes.models import ContentType from django.db.models.signals import post_save from django.urls import reverse from django.dispatch import receiver from django.core import validators class SchoolProfile(models.Model): """Ajoute un champ pour distinguer les groupes écoles des autres.""" group = models.OneToOneField( Group, on_delete=models.CASCADE, related_name="school", ) admins = models.OneToOneField( Group, on_delete=models.SET_NULL, related_name="admin_of", null=True ) phone = models.CharField( max_length=10, help_text="Visible uniquement des administrateurs", verbose_name="Numéro de téléphone pour contacter le responsable des productions", blank=False, null=True, validators=[ validators.RegexValidator('^[0-9]{10}$', "Veuillez entrer un numéro à 10 chiffres."), ] ) def __str__(self): return self.group.name def get_absolute_url(self): return reverse("users:school", kwargs={'pk':self.pk}) def save(self, *args, **kwargs): viewing_right, _ = Permission.objects.get_or_create( codename='view_' + str(self.group.pk), name='Peut voir ' + str(self.group.pk), content_type=ContentType.objects.get_for_model(SchoolProfile) ) if viewing_right not in self.group.permissions.all(): self.group.permissions.add(viewing_right) self.group.save() admins,_ = Group.objects.get_or_create(name='admins') admins.permissions.add(viewing_right) super().save(*args, **kwargs) @receiver(post_save, sender=SchoolProfile) def update_permissions_school(sender, instance, **kwargs): instance.admins,admin_created = Group.objects.get_or_create(name=str(instance.group.pk)+'_admins') admin_right,_ = Permission.objects.get_or_create( codename='manage_' + str(instance.group.pk), name="Administrateur de l'école " + str(instance.group.pk), content_type=ContentType.objects.get_for_model(SchoolProfile) ) admins,_ = Group.objects.get_or_create(name='admins') admins.permissions.add(admin_right) if admin_created: instance.save(update_fields=['admins']) instance.admins.permissions.add(admin_right) instance.admins.save() class UserProfile(models.Model): """Profil d'un utilisateur""" school = models.ForeignKey(SchoolProfile, on_delete=models.SET_NULL, null=True) user = models.OneToOneField(User, on_delete=models.CASCADE) @receiver(post_save, sender=UserProfile) def update_groups(sender, instance, **kwargs): instance.user.groups.add(instance.school.group) @receiver(post_save, sender=User) def update_permission_user(sender, instance, **kwargs): perm,_ = Permission.objects.get_or_create( codename='manage_'+str(instance.pk), name='Peut administrer ' + instance.username, content_type=ContentType.objects.get_for_model(User) ) instance.user_permissions.add(perm) admins,_ = Group.objects.get_or_create(name='admins') admins.permissions.add(perm)