Django Admin覆盖显示的字段值

时间:2017-06-07 18:37:47

标签: django django-models 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转换为人类可读的形式)。

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

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

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"

我尝试返回对象,self,其他一些值。我还试图在不使用可调用的情况下设置值,只是声明" typ =' xxx'"。没有。我可能不明白这一切是如何运作的......

任何想法都将受到赞赏。

2 个答案:

答案 0 :(得分:2)

我认为您的代码不起作用,因为方法名称与字段相同。

你必须更改字段的名称,比如字段元组中的_typ,然后添加一个名为_typ的方法,它返回任何东西或某些obj attr。

即:

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):
        return "pppp"

答案 1 :(得分:1)

您需要创建一个与您的方法名称对应的public class Test { public static boolean find() { int x = 10; int y = 20; int z = 30; change(x,y,z); // call helper method to change this method's variables. System.out.println(x); // should be 20 System.out.println(y); // should be 22 System.out.println(z); // should be 15 } //helper method to be called from find() method private static void change(int changeX ,int changeY,int changeZ) { //change find() variables. x = changeX * 2; y = changeY + 2; z = changeZ /2; } } ,然后从该方法返回任何内容。

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

readonly_field