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
@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'
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With