[Answered ]-Django ClearableInputField in form doesn't render in HTML

1đź‘Ť

By default django ModelForm uses django.forms.ImageField and not ClearableInputField for django.db.ImageField as revealed at https://docs.djangoproject.com/en/1.9/topics/forms/modelforms/#field-types

And I do believe you actually meant ClearableFileInput

ClearableFileInput¶
class ClearableFileInput File upload input: ,
with an additional checkbox input to clear the field’s value, if the
field is not required and has initial data.

How you can make use of it is by changing the widget in the class meta

class PostForm(forms.ModelForm):

    class Meta:
        model = Items
        fields = ('title', 'description', 'image_file')
        widgets = {
            'name': ClearableFileInput(),
        }
👤e4c5

1đź‘Ť

I ended up using the Chrome tool to inspect the HTML source for the page that rendered correctly (but ugly), and used that as a guide to custom build the form in HTML to my liking. This is what I needed to add into my HTML form to get it right:

            {% if item.image_file %}
            Currently:
            <a href="{{item.image_file.url}}"> {{item.image_file.url}}</a>
            <input id="image_file-clear_id" name="image_file-clear" type="checkbox" /> <label for="image_file-clear_id">Clear</label><br />Change: <input id="id_image_file" name="image_file" type="file" /></p>
            {% endif %}

            {% if not item.image_file %}
            <input id="id_image_file" name="image_file" type="file" /></p>
            {% endif %}
👤allardbrain

Leave a comment