渲染时捕获AttributeError:'DecimalField'对象没有属性'attrs'

时间:2011-11-11 19:52:39

标签: django django-forms

继续question。我有以下内容:

models.py

VARIABLE_CHOICES = (
    ('bool', 'On/Off'),
    ('date', 'Date'),
    ('float', 'Number'),
    ('text', 'Text'),
)

class Variable(models.Model):
    template = models.ForeignKey(Template)
    name = models.CharField(max_length=20)
    type = models.CharField(max_length=5, choices=VARIABLE_CHOICES, default=2)
    data = models.CharField(max_length=100, blank=True, null=True)

forms.py

class VariableForm(ModelForm):

    def __init__(self, *args, **kwargs):
        super(VariableForm, self).__init__(*args, **kwargs)

        if self.instance:
            if self.instance.type == 'bool':
                self.fields['data'].widget = BooleanField()
            if self.instance.type == 'date':
                self.fields['data'].widget = DateField()
            if self.instance.type == 'float':
                self.fields['data'].widget = DecimalField()
            if self.instance.type == 'text':
                self.fields['data'].widget = TextInput()
            self.fields['data'].label = self.instance.name

views.py

def template_variables_view(request,tID):
    ...
    templateVariables = Variable.objects.filter(template=template)
    lvForm = []
    for ltVars in templateVariables:
        lvForm.append(VariableForm(instance=ltVars))

我在模板中循环使用lvForm中的表单:

{% for lo in ltvForm %}
    {% for field in lo %}
        <td>{{ field.label }}:</td><td>{{ field }}</td>
    {% endfor %}
{% endfor %}

但我一直收到错误Caught AttributeError while rendering: 'DecimalField' object has no attribute 'attrs'

有什么想法吗?

1 个答案:

答案 0 :(得分:5)

由于某种原因,您正在将数据字段的窗口小部件设置为字段。你应该只是设置字段。

if self.instance.type == 'bool':
    self.fields['data'] = BooleanField()