使用任意方法或属性作为 Django ModelAdmin 对象上的字段?
使用 Django 1.1:
Django 管理文档在 list_display
类属性中的 ModelAdmin 对象上使用任意方法或属性来描述。这是一个很好的机制,可以在模型的列表显示中显示任意信息。但是,更改表单页面本身似乎没有类似的机制。 完成这个有用的小功能以在 ModelAdmin 更改表单页面上显示任意的、非字段派生的信息的最简单方法是什么?
所需设置的具体示例:
class CustomUserAdmin(UserAdmin):
def registration_key(self, obj):
"""Special method for looking up and returning the user's registration key
"""
return 'the_key'
list_display = ('email', 'first_name', 'last_name', 'is_active', 'is_staff',
'registration_key') # <- this works
fields = ('email', 'first_name', 'last_name', 'is_active', 'is_staff',
'registration_key') # <- this DOESN'T work?
Using Django 1.1:
The Django admin docs describe using arbitrary methods or attributes on a ModelAdmin object in the list_display
class attribute. This is a great mechanism for displaying arbitrary information in the list display for a Model. However, there does not appear to be a similar mechanism for the change form page itself. What is the simplest way to accomplish this useful little feature to display arbitrary, non-field-derived information on the ModelAdmin change form page?
A concrete example of the desired setup:
class CustomUserAdmin(UserAdmin):
def registration_key(self, obj):
"""Special method for looking up and returning the user's registration key
"""
return 'the_key'
list_display = ('email', 'first_name', 'last_name', 'is_active', 'is_staff',
'registration_key') # <- this works
fields = ('email', 'first_name', 'last_name', 'is_active', 'is_staff',
'registration_key') # <- this DOESN'T work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我之前已经通过覆盖变更表单的模板并访问模型上的自定义方法来完成此操作。使用
fields
要求管理员尝试为您的方法添加表单字段。I've done this before by overriding the template for the change form, and accessing custom methods on the model. Using
fields
is asking the admin to try to add a form field for your method.请尝试以下操作:
Try the following:
也将该方法添加到“readonly_fields”元组中。
Add the method to the 'readonly_fields' tuple as well.