[Fixed]-Showing value (URL/Thumbnail) from Foreign key in Admin

1👍

Your code is a little confusing, and you should be careful about putting HTML type code in your models. That being said, assuming you are trying to add thumbnails to your admin via foreignkey relations, this would be the easiest approach:

from django.utils.html import format_html

class ProductAdmin(ImportExportModelAdmin):
    resource_class = ProductResource
    list_display = ('prod_name', 'admin_image')
    readonly_fields = ('admin_image',)

    def admin_image(self, obj):
        return format_html('<center><a href="{0}" target="_blank"><img src="{1}"/width="100px"></a></center>', obj.Default_Image.image_default, obj.Default_Image.image_default)
        admin_image.allow_tags = True

Note: Notice the use of format_html(). Always use it in these cases to avoid vulnerabilities, as it escapes possibly malicious code.

Also, you were trying to use image_default.url, which only exists on an ImageField, not a URLField. I removed that as well in favor of just image_default.

👤Hybrid

Leave a comment