How to override field value display in Django admin change form

后端 未结 1 1995
盖世英雄少女心
盖世英雄少女心 2020-12-19 02:41

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

相关标签:
1条回答
  • 2020-12-19 03:18
    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()
    
    0 讨论(0)
提交回复
热议问题