How to add class, id, placeholder attributes to a field in django model forms

前端 未结 9 2084
既然无缘
既然无缘 2020-12-05 00:12

I have a django model like below

models.py

class Product(models.Model):
    name = models.CharField(max_length = 300)
    descripti         


        
9条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-05 00:50

    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'
                })
    

提交回复
热议问题