Search code examples
djangodjango-modelsdjango-admin

How to override displayed field value in a Django Admin page?


I have following model:

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)

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

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"

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.


Solution

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

    Documentation here: 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'