我正在尝试在django ModelForm
中为我的输入添加类,如下所示:
from django import forms
from .models import OrderProject
class OrderProjectForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(OrderProjectForm, self).__init__(*args, **kwargs)
for field in self.fields:
if field.widget.__class__ == forms.widgets.TextInput:
if 'class' in field.widget.attrs:
field.widget.attrs['class'] += 'project-form__input'
else:
field.widget.attrs.update({'class':'project-form__input'})
class Meta:
model = OrderProject
fields = ('name', 'customer', 'area', 'status', 'budget', 'opening_date',
'ending_date',)
不幸的是我收到了错误:
'str' object has no attribute 'widget'
任何想法我做错了什么?
答案 0 :(得分:0)
form.fields
是dict
,其中字段名称为键,表单字段为值。因此,迭代它会产生字符串。改变如下:
for name, field in self.fields.items():
# stuff with field.widget
或者简单地说(如果'东西'没有涉及名称,就像你的代码片段中的情况一样):
for field in self.fields.values():
# stuff with field.widget