Customize ClearableFileInput in django template

≯℡__Kan透↙ 提交于 2021-02-19 05:10:27

问题


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


回答1:


@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'



回答2:


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) 



回答3:


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.



来源:https://stackoverflow.com/questions/34615801/customize-clearablefileinput-in-django-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!