from django.db import models from django.contrib.auth.models import User, Group from django.db.models.signals import post_save from django.urls import reverse from django.dispatch import receiver class SchoolProfile(models.Model): """Ajoute un champ pour distinguer les groupes écoles des autres.""" group = models.OneToOneField( Group, on_delete=models.CASCADE, related_name="students" ) def __str__(self): return self.group.name def get_absolute_url(self): return reverse("users:school", kwargs={'pk':self.pk}) class UserProfile(models.Model): """Profil d'un utilisateur""" school = models.ForeignKey(SchoolProfile, on_delete=models.SET_NULL, null=True, blank=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)