Home > Enterprise >  Mark_safe not render html
Mark_safe not render html

Time:03-06

Trying to generate a thumbnail for preview, the imgtag is not render. I see so many questions about that, and try various solutions unsuccessful.

enter image description here

admin.py

class AdminProductImages(admin.TabularInline):
    model = ProductImages
    form = ProductImagesForm
    extra = 3
    max_num = 3

    def image_tag(self, obj):
        return mark_safe('<img src="%s" style="width:150px;height:150px;"/>') % (obj.image_file_w200_png.url)
    image_tag.short_description = 'xImage'
    image_tag.allow_tags = True

    fields = ( 'image_file_w200_png','image_tag', )
    readonly_fields = ('image_tag',)

    list_display =('image_file_w200_png','image_tag')
    """
    fieldsets = (
        (None, {'fields': ('image_file_w200_png',)}),
    )
    """
    add_fieldsets = (
        (None, {
            'fields': ('image_file_w200_png',),
        }),
    )
    
    class Media:
        js = ('js/img_product_upload.js',)

models.py

class ProductImages(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    image_type = models.CharField(max_length=33,default='image_type')    
    image_file_w200_png = models.ImageField(
        upload_to=upload_to_image_file_w200_png,
        null=True,
        blank=True,
        default='magickhat-profile.jpg'
    )
    #...

forms.py

class ProductImagesForm(ModelForm):
    image_file_w200_png = forms.FileField(widget=forms.ClearableFileInput(
        attrs={
            'class': 'image_add_product'
            }
    ))

    class Meta:
        model = ProductImages
        fields = ['image_file_w200_png',]

After days, can't found the mistake, yet... Some tips are welcome. Django 4.0

CodePudding user response:

You should format the string before wrapping it in a mark_safe, otherwise you will construct a string, and not a string wrapped in a "safe container":

class AdminProductImages(admin.TabularInline):
    # …

    def image_tag(self, obj):
        return mark_safe('<img src="%s" style="width:150px;height:150px;"/>' % obj.image_file_w200_png.url)

or through string interpolation:

class AdminProductImages(admin.TabularInline):
    # …

    def image_tag(self, obj):
        return mark_safe(f'<img src="{obj.image_file_w200_png.url}" style="width:150px;height:150px;"/>')
  • Related