I want to achieve the following in a django form, for a models.ImageField
:
<input type="file">
button ("choose file" button)This seems to me like a normal workflow to select images in a form, but I do not seem to find any fully working solution. All I can find involves hacking around several parts:
forms.FileField
.I have tried to use:
class ImagePreviewWidget(Widget):
def render(self, name, value, attrs=None):
return mark_safe('<img src="/media/%s" width="100px"/>' % escape(value))
For the widget, and I am using this in the form like this:
class DesignCampaignForm(ModelForm):
brand_logo = FileField(widget=ImagePreviewWidget)
This is properly showing the preview of the existing image, but I am unable to click on it to select another file, and even if I was that would not update the preview.
Is there an already available solution for this simple use case?
I haven't been able to find a complete solution, so I have done the following:
ClearableFileInput
, rendering an image and an <input>
element<input>
in the element with CSS, to hide it<input>
element, wrapping the <img>
in a <label>
and using the for
attribute<input>
element changesA gist can be found here.
In my final solution (not yet in the gist), I have added a button for when the image is not yet selected.
edit: Gist only works for Django before version 1.11.x.class ClearableFileInput
has since been gutted and changed
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With