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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With