From 7f7467df48fcaa9d54a78bc7b56bf032cbf35f3f Mon Sep 17 00:00:00 2001 From: Lucas Brandstaetter <lucas@brandstaetter.tech> Date: Sat, 7 Dec 2024 16:39:41 +0100 Subject: [PATCH] Add SingleUUIDObjectMixin We can use this mixin to get an object by its UUID in the URLconf. --- src/backoffice/views/mixins.py | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/src/backoffice/views/mixins.py b/src/backoffice/views/mixins.py index 4546811fd..6942730d5 100644 --- a/src/backoffice/views/mixins.py +++ b/src/backoffice/views/mixins.py @@ -1,10 +1,11 @@ from django.conf import settings from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin from django.core.exceptions import PermissionDenied -from django.http import HttpRequest, HttpResponse +from django.http import Http404, HttpRequest, HttpResponse from django.shortcuts import redirect from django.urls import reverse, reverse_lazy from django.utils.translation import gettext_lazy as _ +from django.views.generic.detail import SingleObjectMixin from rules.contrib.views import PermissionRequiredMixin as RulesPermissionRequiredMixin from core.models.assemblies import Assembly @@ -17,6 +18,7 @@ from core.models.sso import Application class ConferenceRequiredMixinBase: login_url = reverse_lazy('backoffice:login') require_conference = False + _conference: Conference | None = None _conferencemember: ConferenceMember | None = None def __init__(self, *args, **kwargs): @@ -429,3 +431,32 @@ class PasswordMixin: ) return context + + +class SingleUUIDObjectMixin(SingleObjectMixin): + uuid_url_kwarg = 'uuid' + + def get_object(self, queryset=None): + """ + Return the object the view is displaying. + + Require `self.queryset` and a `uuid` argument in the URLconf. + Subclasses can override this to return any object. + """ + # Use a custom queryset if provided; this is required for subclasses + # like DateDetailView + if queryset is None: + queryset = self.get_queryset() + + uuid = self.kwargs.get(self.uuid_url_kwarg) + if uuid is not None: + queryset = queryset.filter(uuid=uuid) + else: + raise AttributeError(f'Generic detail view {self.__class__.__name__} must be called with an object uuid in the URLconf.') + + try: + # Get the single item from the filtered queryset + obj = queryset.get() + except queryset.model.DoesNotExist as exc: + raise Http404(_('No %(verbose_name)s found matching the query') % {'verbose_name': queryset.model._meta.verbose_name}) from exc + return obj -- GitLab