[Fixed]-Django: how to validate inlineformset against another related form


I’m not even sure what the view is doing – it looks like you’re confused on the role of the inlineformset and curry. Firstly, you’re currying the init method of ItemForm with the doc_form, but you haven’t written an init.

Secondly, it looks like you want to be able to edit the Items inside the Document form. So you need the modelformset_factory, and pass in a custom Formset, on which you write a clean method, that has access to everything you need.

from django.forms.models import modelformset_factory

ItemFormSet = modelformset_factory(Item, form=ItemForm, formset=MyCustomFormset)

then in your customformset –

class MyCustomFormset(BaseInlineFormset):

    def clean():
        super(MyCustomFormset, self).clean()
        for form in self.forms:
            #do stuff

Note the clean method on each ItemForm has already been called – this is similar to writing your own clean() on a normal modelform.


OK, so ignore the formset clean, I misunderstood. Just make your document form in the view, pass it along with the formset, then put them all in the same form tag.

<form method="post" action=".">
    {%for field in doc_form %}
    {%for form in formset%}

Then you have access to all the fields in your request.POST, and you can do whatever you want

doc_form = DocumentForm(request.POST)
formset = ItemFormSet(request.POST)
if all([doc_form.is_valid(), formset.is_valid()]):
     #do some stuff

Leave a comment