Search code examples
djangoadminfield

How to override field value display in Django admin change form


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?


Solution

  • 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()