From 14f3123c7287819ddedab4d25d70929484a3bc4b Mon Sep 17 00:00:00 2001 From: Diego Alonso Alvarez Date: Thu, 3 Oct 2024 14:38:31 +0100 Subject: [PATCH] :bug: Add logged user as object owner --- management/views.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/management/views.py b/management/views.py index c2dfce4e..f65bce0f 100755 --- a/management/views.py +++ b/management/views.py @@ -2,6 +2,7 @@ from django.contrib.auth.mixins import LoginRequiredMixin from django.core.exceptions import PermissionDenied from django.db.models import Model +from django.http import HttpResponse from django.shortcuts import get_object_or_404 from django.urls import reverse_lazy from django.views.generic import CreateView, DeleteView, DetailView @@ -321,6 +322,21 @@ def __init__(self, *args, **kwargs): return CustomCreateForm + def form_valid(self, form: forms.ModelForm) -> HttpResponse: + """Set the owner of the object to the current user. + + This is done before saving the object to the database. + + Args: + form (forms.ModelForm): Form with the object data. + + Returns: + HttpResponse: Redirect to the detail view of the created object. + """ + if hasattr(form.instance, "owner"): + form.instance.owner = self.request.user + return super().form_valid(form) + @property def app_label(self) -> str: return self.model._meta.app_label