如何在 Django Admin 中为作为方法//属性的字段重命名列标签?

问题描述 投票:0回答:2

我正在尝试为

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
。问题是管理中的列标签显示为 获取全名

我的问题很简单:我可以覆盖这个吗?如果是的话,怎么办?

感谢您的帮助。

python django unicode admin
2个回答
55
投票

将函数中名为

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:

我编写了一个 admin 方法装饰器,它简化了这个过程,因为一旦我开始使用高度描述性的详细方法名称,在函数上设置属性就会变得大量重复和混乱。

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>'''

0
投票

用装饰器补充

Yuji 'Tomita' Tomita
answer 选项。 Django 现在有一个用于此目的的装饰器:
django.contrib.admin.decorators.display
。 请参阅 Django docs

© www.soinside.com 2019 - 2024. All rights reserved.