Given a model named MainModel
and a RelatedModel
, where the later has a ForeignKey
field to MainModel
:
class
@Yuji 'Tomita' Tomitayou the idea was good, i had the same but once trying, i realized you must also remove specific key from self.inlines
because in change_view
and add_view
method self.get_inline_instances(request)
is called before get_formsets()
. Therefore i moved inlines handling to get_form()
method.
Here is how i sucessfully did it:
class SampleAdmin(ModelAdmin):
inlines = []
def get_inlines(self):
return [SampleInline, SampleInline2]
def get_form(self, request, obj=None, **kwargs):
# due to django admin form fields caching you must
# redefine inlines on every `get_form()` call
if (obj): self.inlines = self.get_inlines()
for inline in self.inlines:
# Here change condition based on your needs and manipulate
# self.inlines as you like (remove, change, etc).
# I used inline.__name__ to detect if this is correct inline
# for my obj
if obj.CONDITION:
self.inlines.remove(inline)
return super(SampleAdmin, self).get_form(request, obj, **kwargs)