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

前端 未结 9 2085
既然无缘
既然无缘 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:43

    I really like Dmitriy Sintsov's answer but it doesn't work. Here's a version that does work:

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field in iter(self.fields):
            self.fields[field].widget.attrs.update({
                'class': 'form-control'
        })
    

    update

    add this condition for better

    if self.fields[field].widget.__class__.__name__ in ('AdminTextInputWidget' , 'Textarea' , 'NumberInput' , 'AdminURLFieldWidget', 'Select'): 
         self.fields[field].widget.attrs.update({ 'class': 'form-control' })
    

提交回复
热议问题