【问题标题】:Customising django ImageField markup in template在模板中自定义 django ImageField 标记
【发布时间】:2017-03-09 20:58:37
【问题描述】:

我有一个表单可以让你上传图片,但我想知道是否可以自定义 Django 生成的标记。

在模型中它被创建为 ImageField:

logo = models.ImageField(blank=True, null=True)

在模板中,我正在创建一个“上传”表单字段,使用

{{ form.logo }}

这是生成的标记:

Currently: <a href="/media/dog.jpg">dog.jpg</a>
<input id="logo-clear_id" name="logo-clear" type="checkbox">
<label for="logo-clear_id">Clear</label>
<br>Change: <input id="id_logo" name="logo" type="file">

我想知道是否可以通过进一步深入来更改该标记,以便例如嵌套复选框以清除其标签中的图像。我还想使用我自己的标记将清除表单字段的选项与上传新字段的选项分开。但是,我找不到任何有关如何执行此操作的文档。我试过输出

{{ logo.logo-clear }}

直接,但这会引发错误。

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    解决方案是创建在我的 forms.py 中使用的小部件的自定义版本:https://docs.djangoproject.com/en/1.10/_modules/django/forms/widgets/#ClearableFileInput

    from django.forms.widgets import ClearableFileInput
    
    class CustomImageFieldWidget(ClearableFileInput):
            template_with_clear = '<label for="%(clear_checkbox_id)s">%(clear)s %(clear_checkbox_label)s</label>'
    
    class OrganisationProfileForm(OrganisationCreateForm):
    
        class Meta(OrganisationCreateForm.Meta):
            widgets = {
                'logo': CustomImageFieldWidget,
            }
    

    【讨论】:

      猜你喜欢
      • 2015-01-20
      • 1970-01-01
      • 2021-07-13
      • 1970-01-01
      • 2012-03-15
      • 2018-06-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多