How can I override the value that is displayed for a field in the Django admin? The field contains XML and when viewing it in the admin I want to pretty-format it for easy readability. I know how to do reformatting on read and write of the field itself, but this is not what I want to do. I want the XML stored with whitespace stripped and I only want to reformat it when it is viewed in the admin change form.
How can I control the value displayed in the textarea of the admin change form for this field?
The way to override fields is to create a Form for use with the ModelAdmin object. This didn't work for me, you need to pass an instance of the widget, rather than the class. The instance worked perfectly, though. I typically would create custom admin forms in the admin.py and not mix them in with forms.py.
You can override forms for django's built-in admin by setting form attribute of ModelAdmin to your own form class. See: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form.
editable=False will make the field disappear from all forms including admin and ModelForm i.e., it can not be edited using any form. The field will not be displayed in the admin or any other ModelForm.
class MyModelForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(MyModelForm, self).__init__(*args, **kwargs)
self.initial['some_field'] = some_encoding_method(self.instance.some_field)
class MyModelAdmin(admin.ModelAdmin):
form = MyModelForm
...
Where, some_encoding_method
would be something you've set up to determine the spacing/indentation or some other 3rd-party functionality you're borrowing on. However, if you write your own method, it would be better to put it on the model, itself, and then call it through the instance:
class MyModel(models.Model):
...
def encode_some_field(self):
# do something with self.some_field
return encoded_some_field
Then:
self.instance.encode_some_field()
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