Search code examples
pythondjangomodeladmin

How to conditionally exclude django admin list display items


I have a quote model in my Django admin, that I set up an admin class for with a list display of some of its fields. One of these fields is a 'partner id'. I have multiple different settings files that extend from a base settings file for whatever environment I'm in. In these settings files, theres a SHOW_PARTNER_ID variable. I want to be able to remove partner_id from the list display if SHOW_PARTNER_ID is set to false, and vice versa. I have a method that returns an empty string for each row of the quote table that doesn't have a partner id, but I would rather just remove the column completely.

class QuoteAdmin(admin.ModelAdmin):
    list_display = ('date', 'device_model', 'first_name', 'last_name', 'customer_address', 'customer_link',
                    'customer_history', 'site_name', 'status', 'partner_id')

    def partner_id(self, obj):
            from django.conf import settings
            try:
                if settings.SHOW_PARTNER:
                    if obj.partner:
                        return u'<a href="/admin/quote/partner/{}/">{}</a>'.format(obj.partner.id, obj.partner.id)
                    else:
                        return ''
                else:
                    return ''
            except Exception as e:
                logging.error(e)
                return ''

Solution

  • Override the get_list_display method of your model admin. The 'original' (source) simply returns the class attribute:

    def get_list_display(self, request):
        """
        Return a sequence containing the fields to be displayed on the
        changelist.
        """
        return self.list_display
    

    Just implement any more complex logic like adding/removing a field based on settings here, e.g.:

    def get_list_display(self, request):
        if not settings.SHOW_PARTNER:
            return self.list_display[:-1]
        return self.list_display