在Django ModelAdmin对象上使用任意方法或属性作为字段?

时间:2010-08-25 14:17:31

标签: python django django-admin

使用Django 1.1:

Django admin docs describe使用list_display class属性中的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?

3 个答案:

答案 0 :(得分:21)

将方法添加到'readonly_fields'元组中。

答案 1 :(得分:4)

尝试以下方法:

class CustomUserAdminForm(forms.ModelForm):
    registration_key = forms.IntegerField()                                 

    class Meta: 
        model = User   

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

答案 2 :(得分:1)

我之前通过覆盖更改表单的模板并访问模型上的自定义方法来完成此操作。使用fields要求管理员尝试为您的方法添加表单字段。