Decent image loader widget in django

Posted by in Software

I’m working on a website where I need to be able to load an image. The default widget is abysmal; it has a url to the current image, a checkbox and a file loader input element. Even styled, it looks pretty bad. So, I’ve taken upon myself to prettify it and get from this:

Default widget

Default widget

to this:

Styled widget

Styled widget

To accomplish the transformation, we need:

After copying the various resources around (e.g. the bootstrap-filestyle in static), we need to create a custom widget for the file input.

and use it in our form:

Now, when the form will be rendered, it’ll use the ImageThumbnailFileInput widget.

The next step is to create the HTML template used in the widget. Following the hints from floppy-forms’ examples, I ended up with something like this:

The code contains an easy_thumbnails reference for image display. You can replace it with e.g. a simple ImageField. Otherwise, it is pretty self-explanatory:

  • There’s a label part of the widget (used by crispy forms to format it nicely)
  • There’s an {% if %} for the case where there’s an image already vs. not (and using a placeholder)
  • A checkbox to clear the image (just like the original widget)
  • A file selector input, styled via bootstrap-filestyle

If you just use it, you’ll find that the read-only field associated with the file input is either unstyled or fills up 100% of the width. The 100% part is the way the .form-control class is defined in bootstrap 3. To fix that, I’ve added a custom class in my customiser style file:

HTH,

Update 1: Thanks to John D. for pointing out my missing reference to easy_thumbnails.


A little experiment: If you find this post and ad below useful, please check the ad out :-)