Show preview image in form

I want to get the following in django form, for models.ImageField:

  • do not show the standard button <input type="file">("select file" button)
  • show a preview of the current image, for already completed models
  • for empty (new) models, show the custom button
  • clicking on the image preview or user button will open the file dialog box to select the image from the user file system.
  • Selecting a new image replaces the user button or a preview of the old image with a preview of the new image.

It seems to me that this is a normal workflow for selecting images in a form, but I did not seem to find a fully working solution. All I can find is hacking into several parts:

I tried using:

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 use it in the following form:

class DesignCampaignForm(ModelForm):

    brand_logo = FileField(widget=ImagePreviewWidget)

This correctly shows a preview of an existing image, but I canโ€™t click on it to select a different file, and even if I were, it would not update the preview.

Is there an already available solution for this simple use?

+4
source share
1

, :

  • ClearableFileInput, <input>
  • <input> CSS,
  • , <input>, <img> <label> for
  • javascript, , <input>.
  • , ,

.

( ), , .

edit: Gist Django 1.11.x.
class ClearableFileInput

+4

Source: https://habr.com/ru/post/1613985/


All Articles