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

Dav*_*Eyk 11 python django django-admin

使用Django 1.1:

Django管理文档描述使用在一个的ModelAdmin物体上的任意方法或属性list_display类属性.这是一种很好的机制,用于在模型的列表显示中显示任意信息.但是,对于更改表单页面本身似乎没有类似的机制.在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?
Run Code Online (Sandbox Code Playgroud)

Dan*_*man 22

将方法添加到'readonly_fields'元组也是如此.


小智 5

请尝试以下操作:

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')
Run Code Online (Sandbox Code Playgroud)