Django Admin覆盖显示的字段值 [英] Django Admin override displayed field value

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

问题描述

我有以下模型:

class Model(models.Model):

    creator = models.ForeignKey(User,related_name='com_creator',on_delete=models.SET_NULL, blank=True, null=True)
    username = models.CharField(max_length=60,default="")
    created = models.DateTimeField(auto_now_add=True)
    body = models.TextField(max_length=10000,default=" ")
    subtype = models.CharField(_("SubType"),max_length=100)
    typ = models.CharField(_("Type"),max_length=50)
    plus = models.ManyToManyField(User,related_name='com_plus', verbose_name=_('Plus'), blank=True)
    is_anonymous = models.BooleanField(_('Stay Anonymous'), blank=True, default=False)

typ和subtype中的值是代码,例如:"6_0_p",(因为原始值太长了,所以我使用代码和dict转换为人类可读的形式).

The values in typ and subtype are codes, like: "6_0_p", (because the original values are ridiculosly long, so I use codes and a dict to translate to human readable form).

问题:如何在django admin中拦截这些值并将其转换为人类可读的形式?

QUESTION: How can I intercept these values in django admin and translate them to human readable form?

这是我到目前为止尝试过的:

This is what i tried so far:

class ModelAdmin(admin.ModelAdmin):
    model = Model
    extra = 1
    exclude = ("username","creator","plus" ) 
    readonly_fields = ('subtype','typ','is_anonymous','created')
    fields = ('body','subtype','typ')

    def typ(self, obj):
        self.typ = "ppp"
        obj.typ = "ppp"
        return "pppp"

我尝试返回对象,自我和其他一些值.我还尝试设置值而不使用可调用对象,而只是声明"typ ='xxx'".没有什么.我可能不明白这整个过程是如何工作的...

I tried returning the object, self, some other value. I also tried to set the value without using a callable just declaring "typ='xxx'". Nothing. I probably don't understand how this whole thing works ...

任何想法都会受到赞赏.

Any ideas will be appreciated.

推荐答案

您需要创建一个与您的方法名称相对应的 readonly_field ,然后从该方法返回任何内容.

You need to create a readonly_field which corresponds to your method name, then return anything from that method.

此处的文档: https://docs.djangoproject.com/en/1.11/ref/contrib/admin/#django.contrib.admin.ModelAdmin.readonly_fields

class MyAdmin(admin.ModelAdmin):
    readonly_fields = ('my_custom_field',)

    def my_custom_field(self, obj):
        return 'Return Anything Here'

这篇关于Django Admin覆盖显示的字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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