What is the quickest way to style django model form fields one by one

I have ModelForm which renders successfully.

this is my forms.py form

class UploadPostsForm(forms.ModelForm):

    class Meta:
        model = Post
        fields = ['title', 'description', 'date', 'file']

this is how it looks in templates

enter image description here

I want it to look like below using bootstrap5

enter image description here

what is the fastest and easiest way to do it? I have found three ways.

1. adding custom template tags

from django import template

register = template.Library()

@register.filter(name='addclass')
def addclass(value, arg):
    return value.as_widget(attrs={'class': arg})

{% load myfilters %}

<form action="/contact/" method="post">
  {{ form.non_field_errors }}
  <div class="fieldWrapper">
    {{ form.subject.errors }}
    {{ form.subject.label_tag }}
    {{ form.subject|addclass:'MyClass' }}
    <span class="helptext">{{ form.subject.help_text }}</span>
  </div>
</form>

2. defining styles in each form fields or all at once

class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel
        widgets = {
            'myfield': forms.TextInput(attrs={'class': 'myfieldclass'}),
        }

3. overriding __init__ method

        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['myfield'].widget.attrs.update({'class': 'myfieldclass'}) 

what is the best way to do this?

django-crispy-forms can solves this problem. It will let you control the rendering behavior of your Django forms in a very elegant and DRY way.

Repo: https://github.com/django-crispy-forms/django-crispy-forms
Simple Tutorial: https://simpleisbetterthancomplex.com/tutorial/2018/11/28/advanced-form-rendering-with-django-crispy-forms.html

Back to Top