如何将类属性添加到ModelForm

时间:2013-12-16 15:04:36

标签: django django-forms

我有模特:

class TestPolja(models.Model):
    class Meta:
        verbose_name = 'Test polja'

        integerPolje1 = models.IntegerField('integerPolje1')
        charPolje1 = models.CharField('charPolje1',max_length = 1024)
        bigint1 = models.BigIntegerField('bigint1',default = 67573737)
        date = models.DateField('date')

和modelForm:

class TestPoljaForm(ModelForm):
    class Meta:
        model = TestPolja

如何更改TestPoljaForm以将class属性添加到<input>代码?

如何添加小部件?

1 个答案:

答案 0 :(得分:2)

您可以使用__init__表单方法执行此操作:

class TestPoljaForm(ModelForm):
    class Meta:
        model = TestPolja

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

        # for example change class for integerPolje1
        self.fields['integerPolje1'].widget.attrs['class'] = 'SOMECLASS'

        # you can iterate all fields here
        for fname, f in self.fields.items():
            f.widget.attrs['class'] = 'SOMECLASS'