I have a django model like below
models.py
class Product(models.Model):
name = models.CharField(max_length = 300)
descripti
I know this is an old question but if someone is still looking to add custom class to all of his form fields, then you can use this one liner
class ProductForm(ModelForm):
class Meta:
model = Product
exclude = ('updated', 'created')
def __init__(self, *args, **kwargs):
super(ProductForm, self).__init__(*args, **kwargs)
custom_attrs = {
'class': 'form-control',
'toggle-data': 'mydiv',
}
# adds our custom_attrs to each element of the form
[self.fields[i].widget.attrs.update(custom_attrs) for i in self.fields]
Field ids should be generated automatically by django, to override other fields:
class ProductForm(ModelForm):
class Meta:
model = Product
exclude = ('updated', 'created')
def __init__(self, *args, **kwargs):
super(ProductForm, self).__init__(*args, **kwargs)
self.fields['name'].widget.attrs\
.update({
'placeholder': 'Name',
'class': 'input-calss_name'
})
You can do the following:
class ProductForm(ModelForm):
name = forms.CharField(label='name ',
widget=forms.TextInput(attrs={'placeholder': 'name '}))