How To: Use Bootstrap 4 In Django

Haris Bin Nasir Avatar

·

·

Django is an extremely capable backend framework. If it doesn’t look good, a functional website isn’t very useful. Users will determine the value of your website based upon it’s aesthetics.

As a result, it is critical that the website’s UI and User Experience are excellent in order for you to increase traffic.

Django is a backend framework, hence front-end development is not its province. We’ll need to learn certain front-end technologies in order to create beautiful Django websites. As a result, we’re going to start with one of the most popular frameworks, Bootstrap.

Here is what the <h1> element styling will look like at the end of this tutorial:

Tutorial Requirements

We will utilize the following dependencies throughout this lesson, which we will install in a moment. Make sure you have Python 3 installed in your environment, preferably 3.7 or newer:

To finish this lesson, we’ll need the following dependencies:

Development environment set up

Change into the directory where you keep your Python virtual environments. Create a new virtualenv for this project using the following command.

I propose creating a distinct directory for your virtualenvs, such as ~/venvs/ (the tilde is a shorthand for your user’s home directory), so you always know where they are.

Copied!
python3 -m venv ~/venvs/djbootstrap4

Activate the virtualenv with the activate shell script:

Copied!
source ~/venvs/djbootstrap4/bin/activate

The command prompt will change when you run the above command, adding the name of the virtualenv to the original command prompt format, so if your prompt is just $, it will now look like this:

Copied!
(djbootstrap4) $

Remember to activate your virtualenv in each new terminal window where you want to use virtualenv dependencies.

We can now install the Django package into the activated but otherwise empty virtualenv.

Copied!
pip install django==3.0.8

Look for output similar to the following to confirm the appropriate packages were installed correctly from PyPI.

Copied!
Collecting django Using cached https://files.pythonhosted.org/packages/ca/ab/5e004afa025a6fb640c6e983d4983e6507421ff01be224da79ab7de7a21f/Django-3.0.8-py3-none-any.whl Collecting sqlparse>=0.2.2 (from django) Using cached https://files.pythonhosted.org/packages/85/ee/6e821932f413a5c4b76be9c5936e313e4fc626b33f16e027866e1d60f588/sqlparse-0.3.1-py2.py3-none-any.whl Collecting asgiref~=3.2 (from django) Using cached https://files.pythonhosted.org/packages/d5/eb/64725b25f991010307fd18a9e0c1f0e6dff2f03622fc4bcbcdb2244f60d6/asgiref-3.2.10-py3-none-any.whl Collecting pytz (from django) Using cached https://files.pythonhosted.org/packages/4f/a4/879454d49688e2fad93e59d7d4efda580b783c745fd2ec2a3adf87b0808d/pytz-2020.1-py2.py3-none-any.whl Installing collected packages: sqlparse, asgiref, pytz, django Successfully installed asgiref-3.2.10 django-3.0.8 pytz-2020.1 sqlparse-0.3.1

We can get started coding tNow that we have all of our essential dependencies installed, we can begin developing the program.

Building our application

Let’s begin coding our application.

To get our project started, we may utilize the Django django-admin tool to generate a boilerplate code structure. Go to the directory where you’re working on your apps. For example, I keep all of my Python projects in /Users/hussain/development/py/. Then, to start a Django project named djbootstrap4, run the following command:

Copied!
django-admin.py startproject djbootstrap4

Note that we use the same name for both the virtualenv and the Django project directory in this example, but you can use other names for your own projects if you like.

If you’ve dealt with Django before, you’ll recognize the django-admin command, which generates a directory called djbootstrap4 with numerous subdirectories, change to this directory.

Copied!
cd djbootstrap4

Create a new Django app within djbootstrap4.

Copied!
python manage.py startapp bootstrap4

Django will create a new folder called bootstrap4. Before we write our views.py code, we should alter the URLs so that the app is accessible.

Open djbootstrap4/djbootstrap4/urls.py. Add the highlighted lines to the URL resolver so that it may check the bootstrap4 app for additional routes that match the URLs requested by this Django app.

Copied!
# djbootstrap4/djbootstrap4/urls.py from django.conf.urls import include from django.contrib import admin from django.urls import path urlpatterns = [ path('', include('bootstrap4.urls')), path('admin/', admin.site.urls), ]

Save djbootstrap4/djbootstrap4/urls.py and open djbootstrap4/djbootstrap4/settings.py. Add the bootstrap4 app to settings.py by inserting the highlighted line:

Copied!
# djbootstrap4/djbootstrap4/settings.py # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap4', ]

Before deploying any code to production, make sure you update the default DEBUG and SECRET KEY values in settings.py. Use the information from the Django production deployment checklist to adequately secure your app so that it does not join the list of compromised web applications.

Save and close settings.py.

Next change into the djbootstrap4/bootstrap4 directory. Create a new file named urls.py to contain routes for the bootstrap4 app.

Add all of these lines to the empty djbootstrap4/bootstrap4/urls.py file.

Copied!
# djbootstrap4/bootstrap4/urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'', views.bootstrap4_index, name="index"), ]

Save djbootstrap4/bootstrap4/urls.py. Open djbootstrap4/bootstrap4/views.py to add the following two highlighted lines. You can keep the boilerplate comment “# Create your views here.” or delete like I usually do.

Copied!
# djbootstrap4/bootstrap4/views.py from django.shortcuts import render def bootstrap4_index(request): return render(request, 'index.html', Array)

Next, create a directory for your template files named templates under the djmaps/maps app directory.

Copied!
mkdir templates

Within djbootstrap4/bootstrap4/templates, create a new file called index.html that contains the Django template language markup.

Copied!
<!DOCTYPE html> <html> <head> <title>First step for bootstrap4</title> </head> <body> <h1>Hello, world!</h1> </body> </html>

Before we start adding the meat of the functionality to the project, we can test out this static page to make sure all of our code is correct. Change to your Django project’s base directory, where the manage.py file is placed. Use the following command to start the development server:

Copied!
python manage.py runserver

With the exception of an unapplied migrations warning, the Django development server should start up without any problems.

Copied!
Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. July 05, 2020 - 10:59:58 Django version 3.0.8, using settings 'djbootstrap4.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C.

Open a web browser and go to “http://localhost:8000”.

Now that our base application is up and running, we can add Bootstrap.

Integrating Bootstrap

It’s time to incorporate Bootstrap into the template so that we may make advantage of its styling.

Open djbootstrap4/bootstrap4/templates/index.html back up and add or modify the following highlighted lines, which are very similar to what you will find in the Bootstrap introduction guide:

Copied!
<!DOCTYPE html> <html lang="en"> <head> <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.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <title>bootstrap4</title> </head> <body> <h1>Hello, world!</h1> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script> </body> </html>

The above additional lines in the head> section introduce a few of meta elements that are needed for Bootstrap’s styling, as well as the Bootstrap stylesheet that is required.

We keep the same <h1> header, which will automatically get the CSS styling. Then there are 3 optional script elements that pull in Bootstrap JavaScript for more advanced features. We are not using them in this tutorial because we just wanted to quickly show how to use the CDN and with this in place you can see in the Bootstrap content docs what you want to add to the template next.

We keep the same <h1> header, which will be styled automatically using CSS. Then, for more sophisticated capabilities, there are three optional script components that pull in Bootstrap and JavaScript. We’re not utilizing them in this tutorial since we just wanted to teach you how to use the CDN quickly, and once you have that in place, you can see what you want to add to the template next in the Bootstrap content docs.

Refresh the page at “http://localhost:8000” and you should see “Hello, world!” change fonts.

If you see that, it means everything works as expected.

Conclusion

The Bootstrap front-end framework is fantastic. I believe we have debunked the idea that on how to use Bootstrap on our websites. Now whats left is just referring the correct CSS files and classes, and you should have a solid looking website.

Please share your thoughts on the Django Bootstrap lesson in the comments area below. We look forward to hearing from you.

Leave a Reply

Your email address will not be published. Required fields are marked *