Files
n3wt-school/Back-End/Subscriptions/views/guardian_views.py
2025-03-20 20:28:12 +01:00

76 lines
2.6 KiB
Python

from django.http.response import JsonResponse
from rest_framework import status
from rest_framework.views import APIView
from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi
from Subscriptions.models import Guardian, Student
from N3wtSchool import bdd
class GuardianView(APIView):
"""
Gestion des responsables légaux.
"""
@swagger_auto_schema(
operation_description="Récupère le dernier ID de responsable légal créé",
operation_summary="Récupèrer le dernier ID de responsable légal créé",
responses={
200: openapi.Response(
description="Dernier ID du responsable légal",
schema=openapi.Schema(
type=openapi.TYPE_OBJECT,
properties={
'lastid': openapi.Schema(
type=openapi.TYPE_INTEGER,
description="Dernier ID créé"
)
}
)
)
}
)
def get(self, request):
lastGuardian = bdd.getLastId(Guardian)
return JsonResponse({"lastid":lastGuardian}, safe=False)
class DissociateGuardianView(APIView):
"""
Vue pour dissocier un Guardian d'un Student.
"""
def put(self, request, student_id, guardian_id):
try:
# Récupérer l'étudiant
student = Student.objects.get(id=student_id)
# Récupérer le guardian
guardian = Guardian.objects.get(id=guardian_id)
# Supprimer la relation entre le student et le guardian
student.guardians.remove(guardian)
# Vérifier si le guardian n'est plus associé à aucun élève
if guardian.student_set.count() == 0: # Utilise la relation ManyToMany inverse
guardian.delete()
return JsonResponse(
{"message": f"Le guardian {guardian.last_name} {guardian.first_name} a été dissocié de l'étudiant {student.last_name} {student.first_name}."},
status=status.HTTP_200_OK
)
except Student.DoesNotExist:
return JsonResponse(
{"error": "Étudiant non trouvé."},
status=status.HTTP_404_NOT_FOUND
)
except Guardian.DoesNotExist:
return JsonResponse(
{"error": "Guardian non trouvé."},
status=status.HTTP_404_NOT_FOUND
)
except Exception as e:
return JsonResponse(
{"error": f"Une erreur est survenue : {str(e)}"},
status=status.HTTP_500_INTERNAL_SERVER_ERROR
)