Skip to content

Commit

Permalink
🐛 Add logged user as object owner
Browse files Browse the repository at this point in the history
  • Loading branch information
dalonsoa committed Oct 3, 2024
1 parent 66c7bff commit 14f3123
Showing 1 changed file with 16 additions and 0 deletions.
16 changes: 16 additions & 0 deletions management/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 14f3123

Please sign in to comment.