How to add class, id, placeholder attributes to a

2019-01-16 18:49发布

I have a django model like below

models.py

class Product(models.Model):
    name = models.CharField(max_length = 300)
    description = models.TextField(max_length = 2000)
    created = models.DateTimeField(auto_now_add = True)
    updated = models.DateTimeField(auto_now = True)

    def __unicode__(self):
        return self.name

forms.py

class ProductForm(ModelForm):
    class Meta:
        model = Product
        exclude = ('updated', 'created')

product_form.py(just an example)

 <form enctype="multipart/form-data" action="{% url 'add_a_product' %}" method="post">
         <div id="name">
           {{form.name}}
         </div> 
         <div id="description">
           {{form.description}}
         </div> 
   </form> 

Actually I want to display/render the html output like below

<input id="common_id_for_inputfields" type="text" placeholder="Name" class="input-calss_name" name="Name">

<input id="common_id_for_inputfields" type="text" placeholder="Description" class="input-calss_name" name="description">

So finally how to add attributes(id, placeholder, class)to the model form fields in the above code ?

8条回答
地球回转人心会变
2楼-- · 2019-01-16 19:39

Slightly modified version of excellent mariodev answer, adding bootstrap class to all form fields, so I do not have to re-create form input widgets for each field manually (short Python 3.x super()):

class ProductForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field in self.Meta.fields:
            self.fields[field].widget.attrs.update({
                'class': 'form-control'
            })
查看更多
兄弟一词,经得起流年.
3楼-- · 2019-01-16 19:42

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'
            })
查看更多
登录 后发表回答