1

I'm working on a django project where I need to permit the user to upload images to the server. Everything's fine except when I want to show an image preview before submitting.

I'm using django-crispy-forms to render the form:

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ["image", "caption"]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.helper = FormHelper()

        self.helper.form_method = "post"
        self.helper.form_action = 'add-post'

        self.helper.add_input(Submit("add-post", "Add Post", css_class='btn-primary btn-dark mt-3'))

This is the HTML template used for rendering the form:

<div class="row justify-content-center mt-4">
    <div class="col-md-8">
            {% crispy form %}
    </div>
</div>

This based on the developer inspector in firefox yields the following input HTML:

<input type="file" name="image" class="custom-file-input" accept="image/*" id="id_image" required="">
<label class="custom-file-label text-truncate" for="id_image">---</label>

After hitting the submit button, the label gets filled with image name. That's exactly what I want.

However, as mentioned I wanted an image preview before submitting so I took look at the following stackoverflow answer and got what I want:

preview image before form submit

Show an image preview before upload

I managed to get an image preview using the following js and HTML:

<div class="row justify-content-center mt-4">
    <img id="image-preview">
</div>

<div class="row justify-content-center mt-4">
    <div class="col-md-8">
            {% crispy form %}
    </div>
</div>

JS:

document.addEventListener('DOMContentLoaded', function() {

    // Show image preview before submitting
    document.getElementById("id_image").onchange = function () {
        var src = URL.createObjectURL(this.files[0]);
        document.getElementById("image-preview").src = src;
    }
})

and now for some reason the label disappears. I tried filling it while reading the image file in the js above but I failed.

Any help is appreciated.

Endless
  • 34,080
  • 13
  • 108
  • 131
user15440172
  • 134
  • 10

0 Answers0