在Django模板中自定义ClearableFileInput [英] Customize ClearableFileInput in django template

查看:116
本文介绍了在Django模板中自定义ClearableFileInput的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 }}

其中 {{picture.clear-picture}} 应该生成复选框以删除旧图片

where {{ picture.clear-picture }} should generate checkbox to delete the old picture

推荐答案

@vadimchin的答案是正确的,但是需要对新版本的Django(2.0及更高版本)进行了一些修改,因为 ClearableFileInput 类已更改.

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

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

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'

并使用所需代码填充customclearablefileinput.html,修改

And fill customclearablefileinput.html with the desired code, modifying the original code of the template as you need.

您还必须在settings.py文件中进行更改,因此Django允许您

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'

这篇关于在Django模板中自定义ClearableFileInput的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆