Adding Bootstrap 4 to Djangox

Kris Pickering · January 21, 2018

The easiest way to get Bootstrap into your Django installation is to use pip. You can manually load the files but I found this to be the simplest solution.

Install using pip:

pip install django-bootstrap4

Add ‘bootstrap4’ anywhere in INSTALLED_APPS inside your settings.py file:

INSTALLED_APPS = [
    'bootstrap4',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

In your template files, add {% load bootstrap4 %} to load the bootstrap4 library.

{% load bootstrap4 %}

{# Display a form #}

<form action="/url/to/submit/" method="post" class="form">
    {% csrf_token %}
    {% bootstrap_form form %}
    {% buttons %}
        <button type="submit" class="btn btn-primary">Submit</button>
    {% endbuttons %}
</form>
 

Configuring Django

Now that we have loaded the main files for Django, we may need to add additional CSS files to get the correct style we are looking for. To do this we need to make use of static files.

Django already knows where to find our static files but we need to create the correct folder inside our app if it does not exist already.

YourProject
├── App1
   ├── migrations
   └── static
└── App2

To keep things well organised we should create a folder called ‘CSS’ to place our stylesheets in.

YourProject
└─── App1
     └─── static
          └─── CSS
               └─── style.css

Once you have put all your stylesheets that you need in our newly created folder, we now need to tell our templates to use them! We can have multiple css files for different pages if needed, you simply need to reference the correct file.

Inside your template file, add {% load staticfiles %} near the top of your template. Our example template should now look like below.

{% load bootstrap4 %}
{% load staticfiles %}

{# Display a form #}

<form action="/url/to/submit/" method="post" class="form">  
    {% csrf_token %}
    {% bootstrap_form form %}
    {% buttons %}
        <button type="submit" class="btn btn-primary">Submit</button>
    {% endbuttons %}
</form>

The last step is to tell our template which css file(s) we want to use. In between your <head> </head> tags, put the following.

<link rel="stylesheet" href="{% static 'CSS/style.css' %}">

Our template folder should now look similar to this.

{% load bootstrap4 %}
{% load staticfiles %}

{# Display a form #}

<head>
<link rel="stylesheet" href="{% static 'CSS/style.css' %}">
</head>

<form action="/url/to/submit/" method="post" class="form">  
    {% csrf_token %}
    {% bootstrap_form form %}
    {% buttons %}
        <button type="submit" class="btn btn-primary">Submit</button>
    {% endbuttons %}
</form>

References

https://github.com/zostera/django-bootstrap4

Twitter, Facebook