From 0f688a8f1c6aaefee0c6a29c0be2dff0bb255e6b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aur=C3=A9lien=20Delobelle?= Date: Mon, 1 Oct 2018 23:03:45 +0200 Subject: [PATCH] kfet -- Stack errors of KPsulOperationForm Delete an error never raised, and avoid duplicate messages. --- kfet/forms.py | 32 +++++++++++++++++++++----------- 1 file changed, 21 insertions(+), 11 deletions(-) diff --git a/kfet/forms.py b/kfet/forms.py index 5fcd30a6..9d0fadd8 100644 --- a/kfet/forms.py +++ b/kfet/forms.py @@ -3,6 +3,7 @@ from decimal import Decimal from django import forms from django.core.exceptions import ValidationError +from django.core import validators from django.contrib.auth.models import User from django.forms import modelformset_factory from django.utils import timezone @@ -321,13 +322,18 @@ class KPsulOperationForm(forms.ModelForm): queryset=Article.objects.select_related('category').all(), required=False, widget = forms.HiddenInput()) + article_nb = forms.IntegerField( + required=False, + initial=None, + validators=[validators.MinValueValidator(1)], + widget=forms.HiddenInput(), + ) class Meta: model = Operation fields = ['type', 'amount', 'article', 'article_nb'] widgets = { 'type': forms.HiddenInput(), 'amount': forms.HiddenInput(), - 'article_nb': forms.HiddenInput(), } def clean(self): @@ -336,22 +342,26 @@ class KPsulOperationForm(forms.ModelForm): amount = self.cleaned_data.get('amount') article = self.cleaned_data.get('article') article_nb = self.cleaned_data.get('article_nb') + errors = [] if type_ope and type_ope == Operation.PURCHASE: - if not article or not article_nb: - raise ValidationError( - "Un achat nécessite un article et une quantité") - if article_nb < 1: - raise ValidationError("Impossible d'acheter moins de 1 article") + if not article or article_nb is None or article_nb < 1: + errors.append(ValidationError( + "Un achat nécessite un article et une quantité")) elif type_ope and type_ope in [Operation.DEPOSIT, Operation.WITHDRAW]: if not amount or article or article_nb: - raise ValidationError("Bad request") - if type_ope == Operation.DEPOSIT and amount <= 0: - raise ValidationError("Charge non positive") - if type_ope == Operation.WITHDRAW and amount >= 0: - raise ValidationError("Retrait non négatif") + errors.append(ValidationError("Bad request")) + else: + if type_ope == Operation.DEPOSIT and amount <= 0: + errors.append(ValidationError("Charge non positive")) + elif type_ope == Operation.WITHDRAW and amount >= 0: + errors.append(ValidationError("Retrait non négatif")) self.cleaned_data['article'] = None self.cleaned_data['article_nb'] = None + if errors: + raise ValidationError(errors) + + KPsulOperationFormSet = modelformset_factory( Operation, form = KPsulOperationForm,