[Fixed]-Add validation in django admin master-detail interface (for detail records)



Iโ€™ve got a simple solution for this, work perfect:


class BarInline(admin.TabularInline):
    model = Bar
    form = BarForm

class FooAdmin(admin.ModelAdmin):
    model = Foo
    inlines = [BarInline,]


class BarForm(forms.models.ModelForm):
    class Meta:
        model = Bar
        fields = ('name',)

    def clean(self):
      data = self.cleaned_data     
      if not item['name'].startswith('Bar'):
         raise ValidationError('Item is not valid.')

So I did not use InlineFormSet and I did not use inlineformset_factory not at all and this is a complete solution that works not just fragments brought here by some untested search



To add validation to your inline formset you can create a custom Form and specify this form to the formset, rather than creating a custom base inline formset:

class MyForm(forms.ModelForm):
    def clean(self):
        cleaned_data = super(MyForm, self).clean()
        for field in cleaned_data:
            # if some meaningful condition for field is met:
                # raise validation error
        return cleaned_data

    class Meta:
        model = ParentModel
        fields = ['fieldA', 'fieldB', ...]

BarInlineFormset = inlineformset_factory(ParentModel, Model, form=MyForm, extra=0, min_num=0)

Do not forget to properly configure your model form, especially its meta class to define model and fields.

Reference: Django documentation: Model form Functions, Creating forms from models.


Leave a comment