Shiva Krishna Bavandla
Shiva Krishna Bavandla

Reputation: 26668

Remove Checkbox for the django image field

I have a model like below

class Book(models.Model):
    name = models.CharField(max_length=56)
    picture = ImageField(upload_to='/max/')

So when editing the Book model from templates like below

<form enctype="multipart/form-data" action="{% url 'edit_book' book_id %}" method="post">
   {% csrf_token %}
   {{book_form.name}}
   {{book_form.picture}}
</form>

if the book record already has an image an extra html checkbox has been

    Currently: 
<a href="/media/product138ba6ccf0d1408d968577fa7648e0ea/assets/bubble.png">media/product138ba6ccf0d1408d968577fa7648e0ea/assets/bubble.png</a>

 <input id="picture-clear_id" name="picture-clear" type="checkbox" /> <label for="picture-clear_id">Clear</label><br />Change: 

<input id="selectedFile" name="picture" type="file" />

So if the book has an image already when it has been created, it also has some checkbox and label before it so how to avoid that checkbox ?

Edit

forms.py

class BookForm(ModelForm):
    class Meta:
        model = Book

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

    super(BookForm, self).__init__(*args, **kwargs)
    self.fields['picture'].widget.attrs = {'id':'selectedFile'} 

Upvotes: 1

Views: 3019

Answers (1)

Ludwik Trammer
Ludwik Trammer

Reputation: 25032

I'm a little surprised to be honest, because what you describe looks like ClearableFileInput widget, while according to the documentation, it is FileInput that is used as a default widget.

Still. Try explicitly choosing FileInput:

from django.forms import ModelForm, FileInput

class BookForm(ModelForm):
    class Meta:
        model = Book
        widgets = {
            'picture': FileInput(),
        }

    def __init__(self, *args, **kwargs):
        super(BookForm, self).__init__(*args, **kwargs)
        self.fields['picture'].widget.attrs = {'id':'selectedFile'} 

Update: I'm not surprised anymore. I investigated the issue, and it turned out there simply was a mistake in Django Docs, now corrected. ClearableFileInput is the default widget, so you need to set FileInput explicitly, as shown above.

Upvotes: 3

Related Questions