Display image in Django admin - Many to many inline admin view

1k Views Asked by At

I have the following models:

class AModel(BaseModel):
    a_id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=200)
    a_images = models.ManyToManyField(BModel)

class BModel(BaseModel):
    images = ImageField(upload_to='/')

I want to display the BModel images in AModel admin form. I am able to do that using

class BModelInline(admin.TabularInline):
    model = AModel.a_images.through

How can I display the image preview in the tabular format in AModel form admin? I already tried overriding formfields, but it doeesn't seem to work.

formfield_overrides = { models.ImageField: {'widget': AdminImageWidget}}

class AdminImageWidget(AdminFileWidget):
    def render(self, name, value, attrs=None):
        output = []
        if value and getattr(value, "url", None):
            image_url = value.url
            file_name=str(value)
            output.append(u' <a href="%s" target="_blank"><img src="%s" alt="%s" width="150px"/></a> ' % \
                (image_url, image_url, file_name))
        output.append(super(AdminFileWidget, self).render(name, value, attrs))
        return mark_safe(u''.join(output))
1

There are 1 best solutions below

0
On

If you just want to display those images in your admin model for AModel, have you tried something like this?:

class AModelAdmin(admin.ModelAdmin):
    readonly_fields = ('images',)

    def images(self, obj):
        html = '<a href="{url}" target="_blank"><img src="{url}" /></a>'
        return format_html(''.join(html.format(url=image.url) for image in obj.a_images))

It can also be doon with a method in the django model