Home Django How to use Bootstrap 4 Forms with Django

How to use Bootstrap 4 Forms with Django

This tutorial fuses two powerful approaches to make your web app creation adventure as easy and painless as possible. If you are a passionate web developer or designer, then the terms Bootstrap and Django have at one point crossed your mind. Django is a fully-fledged framework, while Bootstrap is a fully-fledged tool kit or library. If it were up to some of us, Bootstrap would get the needed upgrade and armor to function as a framework fully. However, those powers are out of our reach.

Nonetheless, one superpower cannot be taken away from this article, which explains the awesome conventions of Bootstrap 4 and why its fusion with Django forms is a time saver for a web developer designer that has considered coupling these two tools.

Understanding Bootstrap

If you are here to learn the ropes and get a better perspective of how this toolkit works, then you are at the right place. Bootstrap is a powerhouse for web application creators and developers. The collective tools that makeup Bootstrap include JavaScript, CSS, and HTML. Moreover, Github is the proud host of this toolkit. The original development objective or intention for Github was to have it solely function for Twitter, who are its original creator. However, its potential contribution and benefit to the growing number of web application creators and developers made it an open-source project whose release took place in 2011.

Its popularity has since caught the web design and development domain like wildfire. These developers and designers favor bootstrap because of its flexibility and ease of use. The main selling criteria that favor Bootstrap include the responsiveness of its design, its unmatched web browser compatibility, and its ideal adaptation to re-usable components. Moreover, we should not forget to mention that learning Bootstrap is literally a walk in the park.

This front-end toolkit is extensive because of its continuous support for JavaScript through programmatic JavaScript API and jQuery plugins. Therefore, applying Bootstrap on any programmable source code editor you want to use for your Django project, like visual Studio Code, is fast and direct. It makes web developers’ work easier as they do not need to waste too much time developing the web app’s front-end. It ensures they spend more time perfecting the application’s logic, which is the back-end.

Bootstrap 4 Forms with Django

The navigation route we took to understand the Bootstrap toolkit has brought us to this point of the article, where we will demystify the Django-crispy-forms application. This crispy-forms app implements Bootstrap 4 as a control mechanism to ease Django’s approaches to render forms. The app keeps the structure of the Django forms inline such that it will not break its default behavior, a case which is evident when you take the manual approach to style your Django forms.

Since the tailoring of this tutorial is on the Bootstrap 4 basis, you will soon learn that all your future Django forms projects only need to make use of some direct symbols to effectively render a simple Django form. Moreover, this approach saves you lots of time since it is easy to set up. To achieve the objective of this article piece, you need to use a Django-Project approach. We are going to mock the set up of a complete Django project to demonstrate the effectiveness of using Bootstrap 4 forms with a Django project.

Django Prerequisites

Step 1:

Make sure you are using the latest Python version; Python 3. You can have it in your Linux system by running the following command sequences.

tuts@codeunderscored:~$  sudo apt update

Make sure you are using the latest Python version; Python 3. You can have it in your Linux system by running the following command sequences.

tuts@codeunderscored:~$  sudo apt install python3.8

This command installs Python 3 on your Linux system. After the installation is successful, you should check the current version of Python on your Linux system to verify that its installation was a success.

tuts@codeunderscored:~$  python3 -V

Python has many packages it works with that are both available for download and under active development. Accessing these packages requires the presence of a package manager. In this case, Python needs the pip tool. We can set it up by running the following command.

tuts@codeunderscored:~$  sudo apt  install -y python3-pip

Therefore, in order to install a Python package through pip, you need to follow the following syntax rule.

tuts@codeunderscored:~$  pip3 install package_name 

To strengthen our Python programming and development environment, your Linux system also needs to consider the installation of other essential Python tools and packages.

tuts@codeunderscored:~$  sudo apt install python-dev libffi-dev build-essential libssl-dev

Step 2:

Ensure that you have an active virtual environment, which is useful when dealing with multiple Django projects. When running multiple projects simultaneously, it helps prevent project conflicts and also makes your project’s resource-sharing mechanism more manageable.

tuts@codeunderscored:~$  sudo apt install -y python3-venv

Creating a virtual environment is as easy as adhering to the structure of the following commands syntax.

tuts@codeunderscored:~$  mkdir my_venvs
tuts@codeunderscored:~$  cd my_venvs

You can use this directory to create and store as many virtual environments as you wish. This approach helps objectify your Django projects to only deal with the needed Python packages defined on a single virtual environment instead of having a single virtual environment run all your projects.

tuts@codeunderscored:~/my_venvs$  python3 -m venv myvenv_name
tuts@codeunderscored:~$  source myvenv_name/bin/activate

Following the above commands sequentially will enable you create and activate a virtual environment called myvenv_name. The instance of your terminal will appear as depicted below for an activated virtual environment.

(myvenv_name) tuts@codeunderscored:~/my_venvs$

Typing deactivate on your Linux terminal will remove the virtual environment’s prefixed name display and your terminal instance will return to its default mode.


Step 3:

This step will enable you to quickly set up a Django project so that we can resume objectifying Bootstrap 4 forms with Django. Your installed virtual environment should be defined and active at this point. You also need to create a projects directory from where you will set up the Django project files to use.

(myvenv_name) tuts@codeunderscored:~$ mkdir django_bootstrap
(myvenv_name) tuts@codeunderscored:~$ cd django_bootstrap
(myvenv_name) tuts@codeunderscored:~/django_bootstrap$

Time to install the Django framework.

(myvenv_name) tuts@codeunderscored:~/django_bootstrap$ pip3 install django>=2.0 

After the above django installation is a success, the next step is to initialize a django project and from there you can work with as many django apps as you wish. For the case of this article, we want to focus on a single django app that will help us understand the implementation of bootstrap 4 forms.

A simple Django project for this article could be initialized as follows.

(myvenv_name) tuts@codeunderscored:~/django_bootstrap$ django-admin startproject djangobootstrap . 

We can now create an app that will be hosted by this Django project.

(myvenv_name) tuts@codeunderscored:~/django_bootstrap$ python3 manage.py startapp bootstrap_forms

This approach is one way of dealing with Django apps. We defined the app we want to host our bootstrap 4 forms, but we are cautious of not re-inventing the wheel. The other approach of dealing with Django apps through a Django project is borrowing the functionality of an already existing app by installing and configuring it under our Django project setting. Therefore, for this tutorial on using Bootstrap 4 Forms with Django to be successful, we will need the services of an external Django app called django-crispy-forms.

The traditional way of styling Django forms required the manual configuration of CSS and JavaScript on the Django templates. This approach often breaks the default behavior of the Django forms from a front-end perspective. Therefore, working with Django forms can present challenging predicaments when accessed from devices with differing resolutions. The django-crispy-forms app has changed the notion regarding this challenging tide. You now have complete control in rendering Django forms. Regardless of our choice to tailor this tutorial with bootstrap 4, the older bootstrap versions can also achieve the set objective.

Installing Django-Crispy-Forms

You can use PIP or PIP3 to install the app.

(myvenv_name) tuts@codeunderscored:~/django_bootstrap$ pip3 install django-crispy-forms

Since this app comes with a set of pre-configured styles, we need to declare the ones we will be using on our app. Therefore, your Django’s settings.py file should mirror the following additional values.

    'bootstrap_forms', # our configured app
    'crispy_forms', # our installed Django-Crispy-App app

CRISPY_TEMPLATE_PACK = 'bootstrap4' # additional bootstrap setting

Setting Up Bootstrap

There are two approaches to have bootstrap set up on your Django project. The first approach is to download its latest version from getbootstrap. The download page from this link will enable you to access both CSS and JS compiled bootstrap versions. The other alternative is for individuals who do not want to download the pre-compiled versions and CSS and JS but rather prefer using a hosted version called Bootstrap CDN. Either approach will work fine, but we can easily meet this article’s objective by using the hosted Bootstrap CDN. Your base.html file should resemble the following file.

<!doctype html>
<html lang="en">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
    <title>Django CodeUnderScored People</title>
    <div class="container">
      <div class="row justify-content-center">
        <div class="col-8">
          <h1 class="mt-2">Django CodeUnderScored People</h1>
          <hr class="mt-0 mb-4">
          {% block content %}
          {% endblock %}

Since our bootstrap 4 forms, Django tutorial, will be prioritizing CSS, we won’t be considering the inclusion of JavaScript.

Django-Crispy-Forms Basic Usage

Consider the existence of a model called Personas. The models.py file depicting this model will look like the file below.

from django.db import models

# Create your models here.
class Personas(models.Model):
    your_name = models.CharField(max_length=130)
    your_email = models.EmailField(blank=True)
    job_title = models.CharField(max_length=30, blank=True)
    your_bio = models.TextField(blank=True)

We need a forms.py file to define the structure of our Django form. It depicts the form of fields we want to populate. For this case, we can go with several fields. It is a simple form where the user will be requested to input their personal details.

from django import forms

class PersonaForm(forms.Form):
    your_name = forms.CharField(label='Your name', max_length=100)
    your_email = forms.EmailField(label='Your email', max_length=150)
    job_title = forms.CharField(label='Your Job Title', max_length=150)
    your_bio = forms.CharField(label='Your Bio Details', max_length=200)

Adding a new Personas Object will require our views.py file to be implemented from the described model. Therefore, your views should resemble the following file.

from django.http import HttpResponseRedirect
from django.shortcuts import render

from .forms import PersonaForm

def get_name(request):
    # Here, we process the form data if the request is POST
    if request.method == 'POST':
        # The successful POST request check should enable us to populate a form instance we will create 
        form = PersonaForm(request.POST)
        # check for the validity of the form:
        if form.is_valid():
            # We use the form.cleaned_data method to process the user's input data
            # ...
            # A new URL rediredtion if the user data processing was a success:
            return HttpResponseRedirect('/thankyou/')

    # If any other method is in play other than PUT, we create a blank form instance
        form = PersonaForm()

    return render(request, 'personal_form.html', {'form': form})

def name_received(request):
    return render (request, 'your-name.html')

We also need some URLs and template files to complete the packaging of this bootstrap 4 forms tutorials. The URLs will be useful in mapping our Views logic to access them from a web browser. The template files are responsible for what we should see from the web browser. Therefore, we will create two template forms, one for receiving the form data we will try to post and the other one for redirecting us to a success page if the form Post method was a success after submitting the posted data.

Create a folder called templates inside the bootstrap_forms app directory you created earlier. This directory should contain our base.html file alongside personal_form.html and your-name.html.

Populate personal_form.html with the following code. It is the template file we will concentrate on since it will depict the behavior of our form’s structure before and after we use Bootstrap 4.

{% extends 'base.html' %}

{% block content %}
  <form method="post">
    {% csrf_token %}
    {{ form }}
    <button type="submit">Save persona</button>
{% endblock %}

Populate your-name.html with the following data. Its usefulness is redirecting us to another page once our form submission is a success. We are not going to pay much attention to it, but we acknowledge its contribution to making our code look more professional.

{% extends 'base.html' %}
{% block content %}
<div style="text-align: center;"><p><strong>Thank You For Your Personal Details!</strong></p></div>
{% endblock %}

Finally, we need to set up our URLs. Your urls.py file inside the djangobootstrap project directory should resemble the following code structure.

from django.contrib import admin
from django.urls import path
from bootstrap_forms import views 

urlpatterns = [
    path('admin/', admin.site.urls),
    path('person/add/', views.get_name), 
    path('thankyou/', views.name_received),  

Before we put this project to the test, we first need to adhere to some house rules before our Django development server can run as required. We will need to makemigrations and migrate our server since we made some changes by initiating a model that stores form data for us. Run the following commands sequentially.

(myvenv_name) tuts@codeunderscored:~/django_bootstrap$ python3 manage.py makemigrations 
(myvenv_name) tuts@codeunderscored:~/django_bootstrap$ python3 manage.py migrate

Afterward, we can now be able to launch our Django server and access the needed urls.

(myvenv_name) tuts@codeunderscored:~/django_bootstrap$ python3 manage.py runserver

Open your browser and access the form template we created using the following url.

Since the personal_form.html template does not have any bootstrap 4 form styling implemented, the web browser view we will receive will be basic.

Django Form Display Without Bootstrap 4
Django Form Display Without Bootstrap 4

It quickly relays to us that the page needs further professional touches to complete its outlook. However, adding a Bootstrap 4 class to the template file quickly reveals a significant improvement in the template form’s outlook.

Django Form with Bootstrap 4 Class
Django Form with Bootstrap 4 Class

We will add crispy_forms_tags into the main form template we defined earlier and see what happens.

{% extends 'base.html' %}

{% load crispy_forms_tags %}

{% block content %}
<form method="post">
    {% csrf_token %}
    {{ form | crispy }}
    <button type="submit" class="btn btn-success">Save persona</button>
{% endblock %}

The new outlook of your form should be as follows.

Django Forms with Activated Crispy Forms Tags
Django Forms with Activated Crispy Forms Tags

You are now a witness to the level of awesomeness the Bootstrap 4 forms’ crispy-forms_tags has enabled us to achieve.

Django-Crispy-Forms Flexibility

What if you want your Django forms to adhere to a different template display structure? It would imply that all your forms templates do not have to mock the vertical field display as depicted above. However, to achieve this level of form template rendering flexibility, we will need to perform some tweaks to that same template.

Update your personal_form.html template to look like the following file.

{% extends 'base.html' %}

{% load crispy_forms_tags %}


{% block content %}
  <form method="post">
    {% csrf_token %}
    <div class="row">
      <div class="col-6">
        {{ form.your_name|as_crispy_field }}
      <div class="col-6">
        {{ form.your_email|as_crispy_field }}
    {{ form.job_title|as_crispy_field }}
    {{ form.your_bio|as_crispy_field }}
    <button type="submit" class="btn btn-success">Save persona</button>
{% endblock %}

As you can see the Django-Crispy-Forms flexibility did not disappoint

The Flexibility of Django Crispy Form s Tags
The Flexibility of Django Crispy Forms Tags

Final Note

This tutorial has covered the most basic and simple approach to achieving complete control of Django forms through bootstrap 4 and the Django-Crisp-Forms. There is a lot more you can do from here. We have created a foundation for you to explore more on using Bootstrap 4 forms with Django. Moreover, you can follow up on Django-Crispy-Form’s official documentation to further explore on the mastery of this Django app and Bootstrap 4 implementation. Its implementation goes beyond Django forms as it gives you the opportunity and control to style and customize a complete Django project.

Sample Filled Django Form with Bootstrap 4
Sample Filled Django Form with Bootstrap 4
Sample Django Form Response
Sample Django Form Response

With Django Crispy forms and Bootstrap 4, the styling of your project templates no longer exists in your to-do list. You have more time to perfect the logic of your Django project.

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More