From dcfd0167e7b9b6505e8c13442cfff89f33113e07 Mon Sep 17 00:00:00 2001 From: korenstin Date: Mon, 8 Jul 2024 17:44:09 +0200 Subject: [PATCH] Security against the cycles --- apps/food/admin.py | 7 +++---- apps/food/views.py | 23 ++++++++++------------- 2 files changed, 13 insertions(+), 17 deletions(-) diff --git a/apps/food/admin.py b/apps/food/admin.py index 23384316..fa32755a 100644 --- a/apps/food/admin.py +++ b/apps/food/admin.py @@ -27,10 +27,9 @@ class TransformedFoodAdmin(admin.ModelAdmin): exclude = ["allergens", "expiry_date"] @transaction.atomic - def save_related(self, *args, **kwargs): - ans = super().save_related(*args, **kwargs) - args[1].instance.update() - return ans + def save_related(self, request, form, *args, **kwargs): + super().save_related(request, form, *args, **kwargs) + form.instance.update() @admin.register(Allergen, site=admin_site) diff --git a/apps/food/views.py b/apps/food/views.py index ec7b7429..13ecfd20 100644 --- a/apps/food/views.py +++ b/apps/food/views.py @@ -17,9 +17,9 @@ from .models import BasicFood, Food, QRCode, TransformedFood from .tables import TransformedFoodTable -class AddIngredientView(ProtectQuerysetMixin, FormView): +class AddIngredientView(ProtectQuerysetMixin, UpdateView): """ - A view to see a qrcode + A view to add an ingredient """ model = Food template_name = 'food/add_ingredient_form.html' @@ -34,28 +34,25 @@ class AddIngredientView(ProtectQuerysetMixin, FormView): @transaction.atomic def form_valid(self, form): form.instance.creater = self.request.user + food = Food.objects.get(pk=self.kwargs['pk']) add_ingredient_form = AddIngredientForms(data=self.request.POST) + if not food.is_ready: + form.add_error(None, _("The product isn't ready")) + return self.form_invalid(form) if not add_ingredient_form.is_valid(): return self.form_invalid(form) - food = Food.objects.get(pk=self.kwargs['pk']) # Save the aliment and the allergens associed for transformed_pk in self.request.POST.getlist('ingredient'): transformed = TransformedFood.objects.get(pk=transformed_pk) - transformed.ingredient.add(food) - transformed.update() - - return super().form_valid(form) + if not transformed.is_ready: + transformed.ingredient.add(food) + transformed.update() + return HttpResponseRedirect(self.get_success_url()) def get_success_url(self, **kwargs): return reverse('food:food_list') - def get_sample_object(self): - return TransformedFood( - name="", - creation_date=timezone.now(), - ) - class BasicFoodUpdateView(ProtectQuerysetMixin, LoginRequiredMixin, UpdateView): """