Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Admin - Inline - 'extra' value based on some condition

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.

like image 502
Sivasubramaniam Arunachalam Avatar asked Nov 26 '25 06:11

Sivasubramaniam Arunachalam


2 Answers

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
like image 116
Langlyin Avatar answered Nov 27 '25 21:11

Langlyin


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 ..

like image 32
Shishir Biyyala Avatar answered Nov 27 '25 23:11

Shishir Biyyala



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!