我正在尝试重新定义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
。问题是管理员中的列标签显示为获取全名。
我的问题很简单:我可以覆盖这个吗?如果是这样,怎么样?
感谢您的帮助。
答案 0 :(得分:32)
将名为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'
我编写了一个简化此过程的admin method decorator,因为一旦我开始使用高度描述性的详细方法名称,在函数上设置属性就会变得大量重复和混乱。
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>'''