From cd436faf9b1db58f891b8034069563d88432a8f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aur=C3=A9lien=20Delobelle?= Date: Sat, 27 Aug 2016 00:14:49 +0200 Subject: [PATCH] =?UTF-8?q?S=C3=A9lection=20fournisseurs=20depuis=20d?= =?UTF-8?q?=C3=A9tail=20d'un=20article?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- kfet/views.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/kfet/views.py b/kfet/views.py index 94e89882..fad87333 100644 --- a/kfet/views.py +++ b/kfet/views.py @@ -548,11 +548,14 @@ class ArticleCreate(SuccessMessageMixin, CreateView): form.add_error(None, 'Permission refusée') return self.form_invalid(form) + # Save ici pour save le manytomany suppliers article = form.save() + # Save des suppliers déjà existant for supplier in form.cleaned_data['suppliers']: SupplierArticle.objects.create( article = article, supplier = supplier) + # Nouveau supplier supplier_new = form.cleaned_data['supplier_new'].strip() if supplier_new: supplier, created = Supplier.objects.get_or_create( @@ -585,6 +588,30 @@ class ArticleUpdate(SuccessMessageMixin, UpdateView): if not self.request.user.has_perm('kfet.change_article'): form.add_error(None, 'Permission refusée') return self.form_invalid(form) + + # Save ici pour save le manytomany suppliers + article = form.save() + # Save des suppliers déjà existant + for supplier in form.cleaned_data['suppliers']: + if supplier not in article.suppliers.all(): + SupplierArticle.objects.create( + article = article, supplier = supplier) + + # On vire les suppliers désélectionnés + for supplier in article.suppliers.all(): + if supplier not in form.cleaned_data['suppliers']: + SupplierArticle.objects.filter( + article = article, supplier = supplier).delete() + + # Nouveau supplier + supplier_new = form.cleaned_data['supplier_new'].strip() + if supplier_new: + supplier, created = Supplier.objects.get_or_create( + name=supplier_new) + if created: + SupplierArticle.objects.create( + article = article, supplier = supplier) + # Updating return super(ArticleUpdate, self).form_valid(form)