Is it possible to dynamically set the 'extra' option in the Django Admin Inline?
For example, If Student class have Address class as Inline. If there is no Address inline's associated with Student, then extra =1. If there is any Address inline's associated with Student, then extra =0.
Just simply override the get_extra method. The following example set extra to 0 for the add view and 10 for the edit view.
class MyInline(admin.TabularInline):
model = MyModel
def get_extra(self, request, obj=None, **kwargs):
return 0 if obj else 10
You can just leverage inheritance..
// based on some condition
kwargs['extra'] = something
.........
return super(*******Inline, self).get_formset(request, obj, **kwargs) // 'defaults.update(kwargs)' takes care of the dynamic overriding
The get_formset method from my project :
def get_formset(self, request, obj=None, **kwargs):
## Put in your condition here and assign extra accordingly
if obj is None:
return super(ImageInline, self).get_formset(request, obj, **kwargs)
current_topic = TopicPage.objects.get(pk = obj.id)
topic_images = ThruImage.objects.filter(topic = current_topic)
kwargs['extra'] = 0
if len(topic_images) <= 3:
kwargs['extra'] = 3 - len(topic_images)
return super(ImageInline, self).get_formset(request, obj, **kwargs)
This is of course, useful only for simple conditionals based off the parent model object ..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With