python - 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 %}
我怎样才能做到这一点?
解决方案
要在后端传递属性,您可以尝试以下操作:
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 %}
它应该只是修改我上面为您的特定用例概述的内容。
希望有帮助!
推荐阅读
- angular - 的初始值
- java - 使用 Mockk 模拟 java 静态方法时附件 ByteBuddyAgent 期间出错
- macos - 如何让 Flutter 项目在 MacOS 上运行以成功使用 Firestore?
- node.js - 如何在 Algolia Search 索引中添加数组作为属性值?
- python - 当您将模型应用于真实数据时,如何检查 ML 中的模型是否适合数据集?
- ios - 如果用户选择该选项,有没有办法可以向 UIAlertController 的 NotNow 按钮添加操作并在 24 小时后触发它?
- ssh - 可以在 SSRS 中使用 ODBC 通过 SSH 隧道连接到 MySQL 数据库吗?
- python - 用字典替换熊猫中给定列的值
- javascript - 在 JavaScript 中修改变量的函数类型是什么?
- electron - 尝试在 Whatsapp 中打开新聊天而不重新加载页面时出错