I have a CreateView of a model with an inlineformset_factory of another model (4 rows, one of each child model). One of the child's model is 'Percentage'. Right now it saves bot the parent and the child model, but I don't have any validation on the percentage field, so the User can easily type '11', '34', '02' and '0' and it will save it.
I want to validate that, before saving anything, the sum of the percentage fields are 100%. My forms.py look like this:
class ParentForm(ModelForm):
class Meta:
model = Parent
fields = ['name', 'observations']
class ChildCreateForm(ModelForm):
class Meta:
model = Child
fields = ['percentage', 'material']
def clean(self):
cleaned_data = super(ChildCreateForm, self).clean()
print(cleaned_data['percentage'])
ChildCreateFormCreateFormSet = inlineformset_factory(Parent, Child, form=ChildCreateForm, extra=4)
So far so good, I can validate every percentage row individually, but I want to validate the total sum.
Should I validate the form with Javascript? There is a way with Django? Or it is best a third option?
You can subclass BaseInlineFormSet and override the clean method. instance with a clean method.
from django.forms import BaseInlineFormSet
class BaseChildFormSet(BaseInlineFormSet):
def clean(self):
super().clean()
total_percentage = sum(f.cleaned_data['percentage'] for f in self.forms)
if total_percentage != 100:
raise forms.ValidationError("Total percentage must be 100")
Then use your class when you create the formset class.
ChildCreateFormCreateFormSet = inlineformset_factory(Parent, Child, form=ChildCreateForm, formset= BaseChildFormSet, extra=4)
See the docs for more info.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With