From 02d83d13a7fa39e4d32bad997aae373b95bba70a Mon Sep 17 00:00:00 2001 From: Rasmus Selsmark Date: Mon, 2 Sep 2024 15:18:01 +0200 Subject: [PATCH] Tillad ikke at slette aktiviteter med inviterede --- members/admin/activity_admin.py | 18 +++++++++++++++++- members/models/activity.py | 10 ++++++++++ members/models/activityinvite.py | 2 +- 3 files changed, 28 insertions(+), 2 deletions(-) diff --git a/members/admin/activity_admin.py b/members/admin/activity_admin.py index adaed33d..789e014d 100644 --- a/members/admin/activity_admin.py +++ b/members/admin/activity_admin.py @@ -1,5 +1,6 @@ -from django.contrib import admin +from django.contrib import admin, messages from django.conf import settings +from django.core.exceptions import ValidationError from django.urls import reverse from django.utils.safestring import mark_safe from django.utils.html import escape, format_html @@ -250,6 +251,21 @@ def formfield_for_foreignkey(self, db_field, request, **kwargs): kwargs["queryset"] = Address.get_user_addresses(request.user) return super().formfield_for_foreignkey(db_field, request, **kwargs) + def delete_queryset(self, request, queryset): + for activity in queryset: + print(activity) + self.delete_model(request, activity) + + def delete_model(self, request, activity): + try: + activity.delete() + messages.success(request, f"Aktivitet \"{activity.name}\" slettet.") + except ValidationError as e: + messages.error(request, e.message) + + except Exception as e: + messages.error(request, f"Fejl: {str(e)}") + fieldsets = [ ( "Afdeling", diff --git a/members/models/activity.py b/members/models/activity.py index afcf3a87..3aee29d2 100644 --- a/members/models/activity.py +++ b/members/models/activity.py @@ -114,6 +114,9 @@ def seats_left(self): def participants(self): return self.activityparticipant_set.count() + def invitations(self): + return self.activityinvite_set.count() + participants.short_description = "Deltagere" def get_min_amount(self, activitytype): @@ -146,3 +149,10 @@ def clean(self): if errors: raise ValidationError(errors) + + def delete(self, *args, **kwargs): + if (self.invitations() > 0 or self.participants() > 0): + raise ValidationError( + f"Aktivitet \"{self.name}\" kan ikke slettes, da der er tilmeldte eller inviterede personer." + ) + super().delete(*args, **kwargs) diff --git a/members/models/activityinvite.py b/members/models/activityinvite.py index c521f014..f36ab510 100644 --- a/members/models/activityinvite.py +++ b/members/models/activityinvite.py @@ -22,7 +22,7 @@ class Meta: unique_together = ("activity", "person") activity = models.ForeignKey( - "Activity", on_delete=models.CASCADE, verbose_name="Aktivitet" + "Activity", on_delete=models.DO_NOTHING, verbose_name="Aktivitet" ) person = models.ForeignKey("Person", on_delete=models.CASCADE) invite_dtm = models.DateField("Inviteret", default=timezone.now)