Rahman Fadhil
PostsTalksAbout

Render Bootstrap Form in Django

May 09, 2019 · 2 min read

Dealing with user input is a very common task in modern web applications. Luckily, Django offers a convenient way to handle user input through forms. You can just build your form schema in your logic and render it through the template context without thinking about it.

By default, Django renders your form fields without any CSS class or styling. That is a great thing if you want to use your custom CSS styling. But in some cases, you want to use CSS libraries like Bootstrap to increase your productivity.

There are several ways to implement styling with CSS libraries to your Django forms. You can render your forms manually, but as far as I know, there is nothing easier than using a third party package called Django Crispy Forms.

Django Crispy Forms is an open-source python package which you can install through Pip. Basically, this package will render your forms with their template packs, which is a set of form input templates that suit with your CSS library.

Installation

Just like any other python packages. You can install using Pip, or Pipenv.

# Using Pip
$ pip install django-crispy-forms

# Using Pipenv
$ pipenv install django-crispy-forms

Then, install the crispy_forms package as an app in your settings.py.

INSTALLED_APPS = (
    # ...
    'crispy_forms',
)

Set template pack

Like I said before, Django Crispy Forms will render our forms with template packs. There are a few template packs available by default. You can find other template packs on the internet.

We need to specify the template pack we want to use in settings.py file.

CRISPY_TEMPLATE_PACK = 'bootstrap4'

Load crispy forms

Now, all you need to do is to load the crispy_forms_tags module in the template file where you want to style your form.

{% load crispy_forms_tags %}

<div>
  {{ form|crispy }}
</div>

That's it! Now your form looks crispy and suits with your CSS library.

Found a typo or problem? Edit on GitHub

Join the Newsletter

Receive quality articles via email every week.