How to override display of field value in admin change form in Django

I want to override the value displayed for a field in a Django admin. The field contains XML, and when viewing it in the administrator, I want to format it fairly evenly for readability. I know how to do reformatting while reading and writing the field itself, but that’s not what I want to do. I want the XML stored with a space to be deleted, and I only want to reformat it when it is viewed in the form of the admin change.

So my question is: how can I control the value displayed in the text field of the admin change form for this field?

+6
source share
1 answer
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 will be what you configured to define spacing / indentation or some other third-party functions that you borrow. However, if you write your own method, it would be better to put it in the model itself, and then call it through an 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() 
+13
source

Source: https://habr.com/ru/post/922774/


All Articles