Add style to Django forms with TailwindCSS

Django Web Development

You can style Django forms with Tailwind CSS without Crispy forms or installing any other external libraries. If you already have Tailwind CSS installed in your Django project, all you need is Django’s built-in “widget” feature, more specifically, the attrs field.

If you need some pointers on getting started with TailwindCSS in your Django project, I highly recommend this video

Once the TailwindCSS installation and basic setup are out of the way, depending on your current code structure, your forms probably follow one of the cases below:

A ModelForm subclass

If you are subclassing ModelForm in your form, you need to add the widgets attribute to the Meta class and then add the style to each attrs field. Example:

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ["title", "content"]

        <mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-luminous-vivid-amber-color">widgets = {</mark>
            "title": TextInput(
                <mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-luminous-vivid-amber-color">attrs={
                    "class": "border border-solid border-slate-300",</mark>
                    "placeholder": "Post Title",
                }
            ),
            "content": Textarea(
                <mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-luminous-vivid-amber-color">attrs={
                    "class": "border border-solid border-slate-300",</mark>
                    "rows": 5,
                }
            ),
        }

A Form subclass

If you are subclassing Django’s forms.Form, you might not have a Meta class. In this case, you add the widget attribute to the form widget itself. Example:

class GuestForm(forms.Form):
    guest = forms.CharField(
        label="Your name",
        max_length=75,
        <mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-luminous-vivid-amber-color">widget=forms.TextInput(</mark>
           <mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-luminous-vivid-amber-color"> attrs={
                "class": "border border-solid border-slate-300",</mark>
                "placeholder": "display name",
            }
        ),
    )

If you found this helpful, please share this article!

The post “Add Style to Django Forms with TailwindCSS” was originally published at flaviabastos.ca