5

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

warownia1
  • 2,771
  • 1
  • 22
  • 30

3 Answers3

7

@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'
mgalgs
  • 15,671
  • 11
  • 61
  • 74
4

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) 
vadimchin
  • 1,477
  • 1
  • 15
  • 17
1

Another solution (on base of @vadimchin's answer) and easier for me is overriding the parameter template_name in the class ClearableFileInput.

You only need to create a new class in forms.py

from django.forms.widgets import ClearableFileInput

class CustomClearableFileInput(ClearableFileInput):
  template_name = "your_path/custom_clearable_file_input.html"

field = forms.FileField(label = ... widget=CustomClearableFileInput(attrs={'placeholder': ...}))

And in the custom_clearable_file_input.html you can put the django code and customize it as you want.