15

我正在尝试为auth.User模型重新定义我的管理页面。一切正常,除了一件事。检查下面的代码:

from django.contrib import admin
from django.contrib.auth.models import User
from access.models import UserProfile


class UserProfileInline(admin.StackedInline):
    model = UserProfile

class UserAdmim(admin.ModelAdmin):
    inlines = [UserProfileInline,]
    list_display = ['id', 'username', 'get_full_name', 'email']


admin.site.unregister(User)
admin.site.register(User, UserAdmim)

如您所见,我希望在模型页面列表中显示的字段之一(由定义list_display)是get_full_name. 问题是 admin 中的列标签显示为Get full name

我的问题很简单:我可以覆盖它吗?如果是这样,怎么做?

谢谢你的帮助。

4

1 回答 1

50

在模型定义中将调用的函数中的属性设置为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>'''
于 2012-08-21T03:56:18.043 回答