开发者

Using arbitrary methods or attributes as fields on Django ModelAdmin objects?

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开发者_JAVA技巧 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?


Add the method to the 'readonly_fields' tuple as well.


Try the following:

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜