Django如何为ModelForm设置自定义属性



我有一个表单。ModelForm"CreateUserForm"。

我想为每个表单字段设置一个属性,以便以后在模板中使用。

在这种情况下,我想设置一个图标名称来指定每个字段应该使用哪个图标名称。

class CreateUserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
icon_names = ['person', 'email', 'enhanced_encryption']
class Meta:
model = User
fields = ['username', 'email', 'password']

我在迭代字段和字段的属性"icon_names"时遇到了问题。我真的无法在不失去功能的情况下压缩((。

目前,我已经通过使用"forloop.parentloop.counter"将迭代组合在一起

{% for field in form %}
<div class="form-group">
<div class="input-field">
<i class="icons">
{% for icon in form.icon_names %}
{% if forloop.parentloop.counter == forloop.counter %}
{{ icon }}
{% endif %}
{% endfor %}
</i>
<input type="text" id="autocomplete-input" class="autocomplete">
<label class="control-label" for="autocomplete-input">{{ field.label_tag }}</label>
</div>
</div>
{% endfor %}

它产生了预期的结果,但似乎是多余的,尤其是如果我想在将来添加另一个字段属性。

做这件事的正确方法是什么?

有两种方法可以做到这一点,都包括在字段小部件上添加一个额外的html属性

  1. 请参阅下面的age字段,我将使用self.fields来获取字段小部件,并在其属性字典上添加额外的图标属性。。。要使其工作,您应该确保它是在对super().__init__(*args, **kwargs)其他人的调用之后出现的,self.fields将不会被填充。。。。当我在小部件类上没有任何其他需要调整的东西时,我会使用这个。https://docs.djangoproject.com/en/2.0/ref/forms/widgets/#styling-小部件实例

  2. 请参阅下面的name字段,您可以在Meta类上执行此操作https://docs.djangoproject.com/en/2.0/topics/forms/modelforms/#overriding-默认字段

形式

class PersonForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['age'].widget.attrs['icon'] = 'age'
class Meta:
model = models.Person
fields = ('name', 'age')
widgets = {
'name': forms.TextInput(attrs={'icon': 'email'})
}

在模板上,当在字段上循环时,id会得到这样的

{% for field in form %}
{{ field.field.widget.attrs.icon }}
{% endfor %}

一个想法是在上下文中传递zipped列表,例如:

context = {'fields_with_icons': zip(form.icon_names, [field for field in form])}

然后

{% for field, icon in fields %}
{{ field }}
{{ icon }}
{% endfor %}

最新更新