Using arbitrary methods or attributes as fields on Django ModelAdmin objects?
使用Django 1.1:
django管理文档描述了在
所需设置的具体示例:
1 2 3 4 5 6 7 8 9 10 11 | 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? |
将该方法也添加到"readonly_fields"元组中。
尝试以下操作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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') |
我以前通过重写变更表单的模板并访问模型上的自定义方法来完成这项工作。使用