Hello,
I’m trying to make a custom validation on a model formset,
to do so I’ve defined a class as follow:
class BaseUnloadFormset(BaseModelFormSet):
def clean(self):
super().clean()
for form in self.forms:
cd = form.cleaned_data
whouse = cd['whouse']
company = cd['company']
product = cd['product']
quantity = cd.get('quantity', None)
movement_date = cd['movement_date']
if quantity:
helper = StockHelper(product, whouse, company, movement_date)
if quantity > helper.stock:
raise ValidationError(f'Attenzione quantità massima disponibile di {product}: {helper.stock}')
and then I use it in the modelformset_factory as so:
UnloadFormSet = modelformset_factory(
model=Unload,
fields='__all__',
extra=5,
form=UnloadForm,
formset=BaseUnloadFormset
)
Problem by using the base modelformset, I will get a key error on every form, even those that I left blank, and should not validate. Moreover, I’ll get a key error even on the first form if I just fill the first field. Instead of getting the “this field is required” built-in red validation message, the server will go down with a key error.
this is the formset with just the first form filled:
the error I get is:
KeyError at /Warehouse/unload/
‘whouse’
class BaseUnloadFormset(BaseModelFormSet):
def clean(self):
super().clean()
for form in self.forms:
cd = form.cleaned_data
whouse = cd['whouse'] # <-- It crashes here, but on the second form not the first
Basically it crashes on the second form, where I’ve not selected the warehouse…which it should not because being a formset, if the form is not filled it should be ignored… or else I should get the django red error.
If I remove the formset=BaseUnloadFormset everything works correctly, but I loose the custom validation that I need.
I tried to follow the docs https://docs.djangoproject.com/en/3.2/topics/forms/modelforms/#overriding-clean-on-a-modelformset, but apparently I’m doing something wrong…
Any suggestions on the matter?
thank you very much