Search code examples
pythondjangodjango-modelsdjango-admin

Is it possible to change the display of a Binaryfield model attribute in the Django admin panel, based on the value of another attribute?


I'm working on a project where I have a model which stores some BinaryField in the database.


class Entry(models.Model):
    ...
    params = models.JSONField()
    body = models.BinaryField()
    ...

params will have a tag with the type of the body item. For example it might be html, and the body will be the html text or an image, and the body could be an image etc.

Right now, the details of Django admin show something like this:


Body:    <memory at 0x7355581f0e80>

Is it possible to change how django admin displays this info, based on the info I have from the other attributes?

Thanks for your time!


Solution

  • Use a property that determines how to render it instead. So:

    from django.contrib import admin
    
    
    class Entry(models.Model):
        # …
        params = models.JSONField()
        body = models.BinaryField()
    
        @admin.display(description='body')
        def render_body(self):
            if self.params is not None:
                # render it one way
                return str(self.body)
            else:
                return 'something else'

    and use this in the .list_display [Django-doc]:

    class EntryAdmin(admin.ModelAdmin):
        list_display = ['render_body']