Okwa
Okwa

Reputation: 77

How to clear an image field in django forms?

So my views look like this:

class PostCreateView(CreateView):
    model = Post
    fields = ['title','content','image', 'status']

The image field currently looks like this:

enter image description here

Is there a way to have like a button to clear the image from the field? The only way to remove the image is to do it from django admin page.

Upvotes: 0

Views: 772

Answers (1)

ha-neul
ha-neul

Reputation: 3248

your html file add a button with an id:

<button id="clear">Clear image </button>

Then in your html, add

{% load static %}

<script>
document.getElementById("clear").addEventListener("click", function () {
    document.getElementById("image").value = "";
}, false);
</script>

Note that you need to use your chrome developor tool to find out what is the id of your file input field, in the above example, I used "image", but it most likely be different. You need to change get.ElementById("image") with the id of your file input field.

Upvotes: 1

Related Questions