Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?
like image 411
David Eyk Avatar asked Aug 25 '10 14:08

David Eyk


3 Answers

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

like image 184
Daniel Roseman Avatar answered Nov 07 '22 07:11

Daniel Roseman


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')
like image 5
Ulf Karlsson Avatar answered Nov 07 '22 09:11

Ulf Karlsson


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.

like image 1
Bob Avatar answered Nov 07 '22 07:11

Bob