[Solved]-How to override field value display in Django admin change form

20👍

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

Leave a comment