问题标题可能有点误导,但我想不出更好的标题。如果标题更好,请编辑标题。
我有以下一组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 %}
我该怎么做?
答案 0 :(得分:1)
要在后端传递属性,您可以尝试执行以下操作:
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 %}
这应该只是修改上面针对特定用例概述的内容的一种情况。
希望有帮助!