Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django iterate over ClearableFileInput widget field

currently have a model that has a model.FileField() attribute, and when rendering in my django template I just iterate over the fields, such as

{% for field in form.visible_fields %}
    <div class="form-group">
    {{field.errors}}
    <label for="{{field.auto_id}}">{{field.label}}</label>
    {{field}}
 {% endfor %}

However, when the template renders the ClearableFileInput widget, I want to add some space between the href and the checkbox for clearing the widget. Any ideas on how to access those specific "parts" of the field?

like image 579
C.B. Avatar asked Jun 07 '26 00:06

C.B.


1 Answers

You have to override the default ClearableFileInput and set those rendering attributes to your taste

class MyClearableInput(ClearableFileInput):
    template_with_initial = '%(initial_text)s: %(initial)s %(clear_template)s<br />%(input_text)s: %(input)s'
    template_with_clear = '%(clear)s <label for="%(clear_checkbox_id)s">%(clear_checkbox_label)s</label>'
    url_markup_template = '<a href="{0}">{1}</a>'

I've put the initial attributes, but you have to change them to reflect your desired output. It's pretty self-explanatory. Then in your form, override the widgets to use this class using the Meta/widgets attribute.

like image 128
Steve K Avatar answered Jun 10 '26 08:06

Steve K