How to add class and other attributes to django form fields

Take your Django forms to the next level by adding custom classes and attributes. Our simple guide shows you how to easily add extra styles to enhance the look of your forms. Try it out now! 

In this tutorial, we will learn how to add CSS class attributes (like form-control), placeholders, IDs, and other attributes in your Django forms.

Let's create a Product Model:

# models.py

from django.db import models

class Product(models.Model):
    title = models.CharField(
         null=False, blank=False, max_length=25, validators=[validate_amazing]
         )
    slug = models.CharField(unique=True, max_length=20)
    quantity = models.PositiveIntegerField()
    price = models.DecimalField(max_digits=5, decimal_places=2)

    def __str__(self):
        return self.title

1. Add form-control class to all fields using for loop.

Now let's write a code to create ProductForm and add CSS class and placeholder attribute.

# forms.py

from django import forms

from .models import Product

class ProductForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for visible in self.visible_fields():
            visible.field.widget.attrs['class'] = 'form-control'
            visible.field.widget.attrs['placeholder'] = visible.field.label

    class Meta:
        model = Product
        fields = '__all__'

The __init__ method sets the class attribute of each field's widget to 'form-control' and the placeholder attribute to the field's label. This allows for easy styling of the form using Bootstrap CSS and also sets the placeholder text for each field to the field's label.

When this form is rendered in a template, each field in the form will have the form-control class and its placeholder text will be the field's label.

In the above code, we are using for loop to add the class and placeholder attribute to all visible fields. But what if you want to add class and placeholder attribute to a specific field, not all fields? Then this is how you can do this.

2. Add form-control class to a specific field.

# forms.py

from django import forms

from .models import Product

class ProductForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
   
        self.fields['title'].widget.attrs['class'] = 'form-control'
        self.fields['title'].widget.attrs['placeholder'] = 'Write product title here'

    class Meta:
        model = Product
        fields = '__all__'

Here we are adding the class and placeholder to the specific field "title".

3. Add other attributes to form fields.

You can also add different attributes like ID, data-* attributes, etc to form fields.

# forms.py

from django import forms

from .models import Product

class ProductForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        
        for visible in self.visible_fields():
            visible.field.widget.attrs['class'] = 'form-control'
            visible.field.widget.attrs['placeholder'] = visible.field.label
    
        # new
        self.fields['price'].widget.attrs['id'] = 'price'
        self.fields['price'].widget.attrs['data-discount'] = '10%'

    class Meta:
        model = Product
        fields = '__all__'

Output:

That's it. If you find it useful then show some love and support by clapping or by buying me coffee. And don't forget to share it with your friends. In case of any problem, you can comment here or you can also directly approach me through my LinkedIn.

Related Articles.

Mastering form validation in Django: A complete guide

How to add date input widget in django forms

I would greatly appreciate it if you subscribe to my YouTube channel, Let's Code More

 ⋅  1 comment has been posted.
    Jan. 24, 2024, 5:15 p.m. - Noë  
    And what do I do when I want to add a class to the <label>, because I would like to style that as well
    Reply

Your comment

Required for comment verification
claps