[Fixed]-How can I rename a column label in Django Admin for a field that is a method//property?

53👍

Set an attribute in your function called short_description to your desired label in your model definition.

# note, this must be done in the class definition;
# not User.get_full_name.short_description
get_full_name.short_description = 'my label' 

Alternatively, if you don’t want to pollute your model with admin specific code, you can set list_display to a method on the ModelAdmin which takes one argument: the instance. You’ll also have to set readonly_fields so that the admin doesn’t try to look up this field in your model. I prefix admin fields with _ to differentiate.

class MyAdmin(...):
    list_display = ('_my_field',)
    readonly_fields = ('_my_field', )     

    def _my_field(self, obj):
        return obj.get_full_name()
    _my_field.short_description = 'my custom label'

Update:

Note that this will break default admin ordering. Your admin will no longer sort fields by clicking the label. To enable this functionality again, define an admin_order_field.

def _date_created(self, obj):
    return obj.date_created.strftime('%m/%d/%Y')
_date_created.short_description = "Date Created"
_date_created.admin_order_field = 'date_created'

Update 2:

I’ve written an admin method decorator that simplifies this process, because once I started using highly descriptive verbose method names, setting attributes on the function became massively repetitive and cluttering.

def admin_method_attributes(**outer_kwargs):
    """ Wrap an admin method with passed arguments as attributes and values.
    DRY way of extremely common admin manipulation such as setting short_description, allow_tags, etc.
    """
    def method_decorator(func):
        for kw, arg in outer_kwargs.items():
            setattr(func, kw, arg)
        return func
    return method_decorator


# usage
class ModelAdmin(admin.ModelAdmin):
    @admin_method_attributes(short_description='Some Short Description', allow_tags=True)
    def my_admin_method(self, obj):
        return '''<em>obj.id</em>'''

Leave a comment