如何覆盖Django管理员更改表单中的字段值显示 [英] How to override field value display in Django admin change form

查看:125
本文介绍了如何覆盖Django管理员更改表单中的字段值显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想覆盖Django管理员中显示的字段值。该字段包含XML,并且在管理员中查看它时,我想要漂亮的格式化它以便于阅读。我知道如何对现场本身的读写进行重新格式化,但这不是我想要做的。我想要将XML存储的空格删除,我只想在管理员更改表单中查看时重新格式化。

I am wanting to 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.

所以我的问题是,我如何控制值显示在该字段的管理员更改表单的文本区域中

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

推荐答案

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
    ...

其中, some_encoding_method 将是您设置确定间距/缩进或您借用的其他第三方功能。但是,如果您编写自己的方法,最好将其放在模型本身,然后通过实例调用:

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

然后:

self.instance.encode_some_field()

这篇关于如何覆盖Django管理员更改表单中的字段值显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆