在模型定义中将调用的函数中的属性设置为short_description
所需的标签。
# note, this must be done in the class definition;
# not User.get_full_name.short_description
get_full_name.short_description = 'my label'
或者,如果您不想用管理员特定的代码污染您的模型,您可以设置list_display
一个方法,该方法ModelAdmin
接受一个参数:实例。您还必须进行设置readonly_fields
,以便管理员不会尝试在您的模型中查找此字段。我在管理字段前加上_
区分。
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'
更新:
请注意,这将破坏默认的管理员排序。您的管理员将不再通过单击标签对字段进行排序。要再次启用此功能,请定义一个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'
更新 2:
我编写了一个管理方法装饰器来简化这个过程,因为一旦我开始使用高度描述性的详细方法名称,在函数上设置属性就会变得非常重复和混乱。
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>'''