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"]

        widgets = {
            "title": TextInput(
                attrs={
                    "class": "border border-solid border-slate-300",
                    "placeholder": "Post Title",
                }
            ),
            "content": Textarea(
                attrs={
                    "class": "border border-solid border-slate-300",
                    "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,
        widget=forms.TextInput(
            attrs={
                "class": "border border-solid border-slate-300",
                "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

Related Posts