2013-12-16 123 views
1

我有模式:如何類屬性添加到的ModelForm

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>標籤?

如何添加小部件?

回答

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' 
+0

和每個領域我必須重複低谷各個領域,並添加小部件? – milandjukic88

+0

@ milandjukic88檢查更新 – ndpu

+0

瞭解它:)。謝謝! – milandjukic88

2
class TestPoljaForm(ModelForm): 
    integerPolje1 = forms.IntegerField(widget=forms.TextInput(attrs={'class': 'myclass'})) 

    class Meta: 
     model = TestPolja 
+0

我寧願這種方法。 – karthikr

+0

這也可以,但是我想爲所有字段設置相同的類名。 – milandjukic88

相關問題