[Fixed]-Using arbitrary methods or attributes as fields on Django ModelAdmin objects?

31👍

Add the method to the ‘readonly_fields’ tuple as well.

5👍

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

1👍

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.

👤Bob

Leave a comment