首页 > 解决方案 > Django - 表单 - 将自定义属性分配给 forms.py 中的表单

问题描述

问题标题可能有点误导,但我想不出更好的标题。如果你有更好的标题,请编辑标题。

我有以下一组models.py和forms.py`

# models.py
class BHA_Component(models.Model):
    field_1 = models.CharField(max_length=100)
    field_2 = models.CharField(max_length=100)
    field_3 = models.CharField(max_length=100)

# forms.py
class BHA_Component_Form(forms.ModelForm):
    class Meta():
        fields = '__all__'

我想为每个字段创建自定义属性,以便我可以识别它在前端的字段类型,并为每个字段类型分配一个类。

像这样的东西:

在此处输入图像描述

有些字段是空白的,有些是灰色的,有些是紫色的,有些有复选框。这些是通过在前端手动为每个字段指定一个特定的 HTML 类来完成的。但是,我想在后端为每个字段提供一些属性,并在前端识别这些属性。所以,像这样:

{% for field in bha_component_form %}

  {% if field.custom_attribute == 'option_1' %}
    {{ field|add_class:"has_checkbox"}}
  {% else if field.custom_attribute == 'option_2' %}
    {{ field|add_class:"blue_background"}}
  {% else %}
    {{ field|add_class:"plain"}}
  {% endif %}

{% endfor %}

我怎样才能做到这一点?

标签: pythondjangodjango-modelsdjango-forms

解决方案


要在后端传递属性,您可以尝试以下操作:

email = forms.EmailField(widget=forms.EmailInput(attrs={'class': "form_control form-control-lg", 'placeholder': "Email"}), required=True, )

因此,对于您的具体情况:

models.py

class BHA_Component(models.Model):
    field_1 = models.CharField(max_length=100, widget=forms.TextInput(attrs={'custom_attribute': "option_1") })
    field_2 = models.CharField(max_length=100, widget=forms.TextInput(attrs={'custom_attribute': "option_2") })
    field_3 = models.CharField(max_length=100, widget=forms.TextInput() })

应该是在您的模板中使用类似这样的内容:

{% for field in bha_component_form %}
  {% if field.widget.attrs.custom_attribute == 'option_1' %}
    {{ field|add_class:"has_checkbox"}}
  {% else if field.widget.attrs.custom_attribute == 'option_2' %}
    {{ field|add_class:"blue_background"}}
  {% else %}
    {{ field|add_class:"plain"}}
  {% endif %}
{% endfor %}

它应该只是修改我上面为您的特定用例概述的内容。

希望有帮助!


推荐阅读