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

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

    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]
    
    0 讨论(0)
  • 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'
                })
    
    0 讨论(0)
  • 2020-12-05 00:50

    You can do the following:

    class ProductForm(ModelForm):
        name = forms.CharField(label='name ', 
                widget=forms.TextInput(attrs={'placeholder': 'name '}))
    
    0 讨论(0)
提交回复
热议问题