【问题标题】:Customize ClearableFileInput in django template在 django 模板中自定义 ClearableFileInput
【发布时间】:2016-04-09 12:29:53
【问题描述】:

我有一个将profile_picture=ImageField 字段设置为初始值的表单。它使用ClearableFileInput 小部件。我需要自定义模板中的表单,所以我不能简单地使用{{ form.profile_picture}}。如何拆分字段元素并获得如下所示的内容:

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

{{ picture.clear-picture }} 应该在哪里生成删除旧图片的复选框

【问题讨论】:

    标签: django django-forms django-widget


    【解决方案1】:

    @vadimchin's answer 是正确的,但它需要对新版本的 Django(2.0 及更高版本)进行一些修改,因为 ClearableFileInput 类已更改。

    您必须通过在模板目录中创建另一个模板来覆盖ClearableFileInputtemplate_name 属性。例如:

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

    并用所需的代码填充customclearablefileinput.html,根据需要修改模板的the original code

    您还必须在 settings.py 文件中进行更改,因此 Django 允许您从项目模板目录中 override widget templates:将 'django.forms' 添加到 INSTALLED_APPS,然后添加以下代码:

    FORM_RENDERER = 'django.forms.renderers.TemplatesSetting'
    

    【讨论】:

      【解决方案2】:

      您可以覆盖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>'
      

      render方法,

      覆盖后,设置

        class ExForm(forms.Form):
             image = ImageField(widget=CustomClearableFileInput) 
      

      【讨论】:

        【解决方案3】:

        另一个解决方案(基于@vadimchin 的回答)对我来说更容易的是覆盖class ClearableFileInput 中的参数template_name

        只需要在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': ...}))
        
        

        您可以在 custom_clearable_file_input.html 中输入the django code 并根据需要对其进行自定义。

        【讨论】:

          猜你喜欢
          • 2013-11-15
          • 2015-01-20
          • 2016-07-09
          • 2015-11-06
          • 2013-09-29
          • 2017-02-20
          • 2012-03-05
          • 1970-01-01
          • 2019-04-03
          相关资源
          最近更新 更多