【问题标题】:Custom method for field字段的自定义方法
【发布时间】: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


    【解决方案1】:

    如果使用自定义过滤器则得到

    from django import template
    from django.template.defaultfilters import stringfilter
    
    from .utils import name_to_image_path
    
    register = template.Library()
    
    
    @register.filter
    @stringfilter
    def image_uri(value):
        return name_to_image_path(value)
    

    然后在模板{{ form.label | name_to_image_path }} 更多信息在这里: https://docs.djangoproject.com/en/2.2/howto/custom-template-tags/

    【讨论】:

      猜你喜欢
      • 2019-06-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-03
      • 1970-01-01
      • 2012-06-23
      • 2014-01-09
      • 2017-08-26
      • 1970-01-01
      相关资源
      最近更新 更多