【发布时间】:2019-08-04 20:43:17
【问题描述】:
我使用 cookiecutter django 为我的第一个应用程序创建了一个项目和 django 构建器,以便快速启动和运行。我正在使用清晰的表单,我想用图像替换默认复选框。
我有一个只有布尔字段的模型 - 我想根据表单中的字段设置为真或假来显示图像。
我有一个函数可以将列名映射到可以在模板中使用的图像路径,但我不知道如何在不向模板添加函数调用的情况下执行此操作
理想情况下,我应该有一个 field.image 方法,我可以将它插入到 src 元素中,我的函数调用看起来像这样
image_src = image_path(field.label)
正如我所见,对 field.label 的最佳访问在此模板中。
这是我要使用的自定义模板
{% load crispy_forms_field %}
<li>
{% crispy_field field 'class' 'custom-control-input' %}
<label for="{{ field.id_for_label }}"><img src="{{ field.image }}" alt="{{ field.label }}"/></label>
</li>
这是我的forms.py
class ProtectiveEquipmentForm(forms.ModelForm):
class Meta:
model = ProtectiveEquipment
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.layout = Layout(
Fieldset(
'first arg is the legend of the fieldset',
Field('head_protection', 'eye_protection',
'template="graphical_checkbox.html"),
template="graphical_checkbox_list.html"
),
ButtonHolder(
Submit('submit', 'Submit', css_class='button white')
)
)
super(ProtectiveEquipmentForm, self).__init__(*args, **kwargs)
【问题讨论】:
标签: python django django-crispy-forms