Search code examples
djangoadmininlines

Django Admin conditional display inlines based on models property


I've got marketplace models with fields:

class VacationEvent(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    process_fba = models.BooleanField(default=True)

    @property
    def has_amazon_fba_vacation(self):
        return hasattr(self, 'amazon_fba_vacation')

And in admin.py:

class FBAInline(admin.StackedInline):
    model = AmazonFBAVacation
    can_delete = False
    verbose_name_plural = 'amazon fba vacation'
    fk_name = 'event'

I need to display conditionally FBAInline class when creating\updating VacationEventAdmin. list_filter shows true\false values of "process_fba" field, so if it is true - FBAInline should be displayed:

@admin.register(VacationEvent)
class VacationEventAdmin(admin.ModelAdmin):
    inlines = []
    list_display = ('id', 'user', 'holiday_name', 'start_date', 'end_date', 'process_fba', 'process_fbm', 'process_walmart', 'process_ebay')
    list_filter = ['process_fba', 'process_fbm', 'process_walmart', 'process_ebay', 'status',]
    search_fields = ['holiday_name', 'user__username']

# if VacationEvent.process_fba and VacationEvent.has_amazon_fba_vacation:
#     inlines.append(FBAInline)

# try:
#     getattr(VacationEvent, 'process_fba')
# except AttributeError:
#     print "doesn't"
# else:
#     inlines.append(FBAInline)

I tried getting attr but don't understant how to compare field values for admin. Thanks for any help.


Solution

  • Override get_formsets_with_inlines method

    get_formsets_with_inlines(self, request, obj=None):
        for inline in self.get_inline_instances(request, obj):
            if obj and obj.has_amazon_fba_vacation:
                yield inline.get_formset(request, obj), inline