Customize how ModelForm renders ImageField?

Hello,

I got a bit stuck - perhaps because I don’t know what precisely to google for.

In my project, I am mostly using the {{ form.as_p }} approach which might not be ideal but so far it worked quite well.

Some forms display images (models.ImageField) and I would like to customize the HTML result. Specifically I want to render preview of the image if the form has one.

Can this reasonably be achieved with my setup? Or should I just create the HTML markup manually and add the preview this way? This form has quite a few fields so doing manual HTML is quite a chore.

Thanks!

How specifically do you want to customize the result? There’s a lot you can do at the “form” layer, either with attributes on the field or changes you make to the fields collection in __init__.

Right, good point.

I want to render the image (if the field has one)

So ideally I would want to add something like this right after the image input:

<div class="image-preview">
    <img src="{{ field.file.url }}" />
</div>

My gut reaction would be to supply an alternate template to render that field. (You could use the if tag to only render the image if the instance was supplied.) There are probably other ways to do this, but I’m not thinking of any reasonable ones at the moment.

1 Like

Hmm perhaps something like this - Customising django ImageField markup in template - Stack Overflow

This post suggests overriding how the widget for particular field.

Severely out-of-date relative to what’s currently available, but yes, that answer is along the right idea.

See The form rendering API | Django documentation | Django (and the pages it links to) for how it can be done now.

Thanks!

Created my own “widget” with custom template based on the one that Django uses

class ImageFieldWidgetWithPreview(ClearableFileInput):
    template_name = 'overrides/form_image_field_widget_with_preview.html'

This post also helped a bit: Overriding Field Widgets In Django Doesn't Work. Template Not Found. The Solution ⚡ | TimOnWeb