0๐
โ
Iโve got a simple solution for this, work perfect:
admin.py
class BarInline(admin.TabularInline):
model = Bar
form = BarForm
@admin.register(Foo)
class FooAdmin(admin.ModelAdmin):
model = Foo
inlines = [BarInline,]
forms.py
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
๐คSerjik
1๐
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.
๐คWtower
- How to show formset from two related models?
- How to integrate Django API project with nodejs and react on frontend?
Source:stackexchange.com