Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customize ClearableFileInput in django template

I've got a form with profile_picture=ImageField field set to the initial value. It's using ClearableFileInput widget. I need to customize the form in the template, so I can't simply use {{ form.profile_picture}}. How can I split field elements and obtain something which looks like this:

{{ with picture=form.profile_picture }}
{{ picture.label_tag }}
<a href="{{ picture.url }}">
  <img src="{{ picture.url }}">
</a>
{{ picture.clear-picture }}

where {{ picture.clear-picture }} should generate checkbox to delete the old picture

like image 834
warownia1 Avatar asked Aug 31 '26 06:08

warownia1


2 Answers

@vadimchin's answer is correct, but it requires a little modification for new versions of Django (2.0 onwards), since the ClearableFileInput class has changed.

You have to override the template_name attribute of ClearableFileInput, by creating another template in your templates directory. For example:

class CustomClearableFileInput(ClearableFileInput):
    template_name = 'widgets/customclearablefileinput.html'

And fill customclearablefileinput.html with the desired code, modifying the original code of the template as you need.

You also have to make changes in your settings.py file, so Django lets you override widget templates from your projects template directory: Add 'django.forms' to INSTALLED_APPS, and then add this code:

FORM_RENDERER = 'django.forms.renderers.TemplatesSetting'
like image 173
Fernando Jesus Garcia Hipola Avatar answered Sep 02 '26 07:09

Fernando Jesus Garcia Hipola


You can override ClearableFileInput

class CustomClearableFileInput(ClearableFileInput):
    template_with_initial = (
        '%(initial_text)s: <a href="%(initial_url)s">%(initial)s</a> '
        '%(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>'

look at render method,

and after override, set

  class ExForm(forms.Form):
       image = ImageField(widget=CustomClearableFileInput) 
like image 32
vadimchin Avatar answered Sep 02 '26 06:09

vadimchin