1: Adding Bootstrap to your Django project


Now that you have installed and set up a basic Django project, it's time to customize and edit the project to create a responsive web app. For this tutorial, you will be creating a monetizable blog/product showcase. The web app will focus on a particular product category, in this case headphones, and include the ability to post blog articles and add product cards where users can submit their own rankings for a given pair of headphones. Each product card will show a pair of headphones, include a ranking submission, and contain a "Buy now" affiliate link to the product on Amazon.

Our goal is to teach web development by offering an interesting and more motivational project to code. By demonstrating how to launch a web app with the potential to generate revenue using affiliate marketing, we hope to provide the skills and inspiration to create your own amazing site and kickstart your coding journey.

 

Add the HTML document structure to home.html

env > mysite > main > templates > main > home.html

<!DOCTYPE html>
<html>
  <head>
    <title>Encore</title>
  </head>
  <body>   
    <p>Hello world!</p>
  </body>
</html>

Add the document type declaration, html, head, title, and body elements to the document. The title of the web page will be "Encore" for this project. Save the file with Ctrl + S.

 

Code-it-yourself: Add Bootstrap to home.html

 

env > mysite > main > templates > main > home.html

<!DOCTYPE html>
<html>
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Encore</title>
    <!--Bootstrap CSS-->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
  </head>
  <body>
    <p>Hello world!</p>
    <!-- Optional Javascript -->
    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" 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.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
  </body>
</html>

Now add the Bootstrap CSS and JS CDNs to the body element. Save the file. 







2: Adding a Bootstrap navbar


Let's start by adding a navigation bar to the top of the homepage. The navigation bar on this site will help users easily find products, the blog, and contact information.

 

 

Add the Bootstrap navbar to the home.html

env > mysite > main > templates > main > home.html

<!DOCTYPE html>
<html>
  <head>
    ...
  </head>
  <body>

    <!--Navbar-->
    <nav class="navbar navbar-expand-sm navbar-light bg-light">
      <a class="navbar-brand" href="/">Encore</a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarText" aria-controls="navbarText" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarText">
        <ul class="navbar-nav mr-auto">
          <li class="nav-item">
            <a class="nav-link" href="">Products</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="">Blog</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="">Contact</a>
          </li>
        </ul>
      </div>
    </nav>

    <!-- Optional Javascript -->
    ...
  </body>
</html>

Right after the opening body tag delete <p>Hello world!</p> and add the above code to create a navigation bar. This navigation bar is based on the navbar available in the Bootstrap documentation. One thing to note, the navbar-brand anchor element has href="/" that, when clicked, goes to the homepage. You'll also notice we added several nav-links to the navbar using an unordered list. We will leave these hyperlinks blank for now given we currently don't have any other pages to link to.

Save the file and reload the http://127.0.0.1:8000/ browser page and the Bootstrap navigation bar should appear at the top of the page.

Add Bootstrap navbar








3: Adding a call-to-action section


Add a CTA below the navbar

env > mysite > main > templates > main > home.html

<!DOCTYPE html>
<html>
  <head>
    ...
  </head>
  <body>

    <!--Navbar-->
    ...

    <!--CTA-->
    <div class="container">
      <div class="row">
        <div class="col-sm-12 col-md-12 col-lg-6 pb-4">
          <h1 class="display-4 font-weight-bold">Elevate your listening</h1>
          <h5>Everyday headphones that make your favorite artists sound like their performing a never-ending encore.</h5>
        </div>
        <div class="col-sm-12 col-md-12 col-lg-6">
        </div>
      </div>
    </div>

    <!-- Optional Javascript -->
    ...
  </body>
</html>

First create an HTML comment that indicates a call-to-action (CTA) section. Then add a container for the CTA message below it. This code block will go directly after the navbar element.

Next, nest a division element with class attribute row in the container.  Add two more division elements with column class attributes in the rowThese two responsive columns will be full-screen (col-sm-12 col-md-12) on small and medium devices and half-screen (col-lg-6) on large devices.

Add a heading one element with class attributes display-4 and font-weight-bold inside the first column. Then, add a heading five element on the next line. Fill in both header elements with the appropriate text.  Finally add padding-bottom (pb-4) to the first column so the columns do not touch when they are stacked vertically on smaller devices.

 

Improve the CTA padding

env > mysite > main > templates > main > home.html

<!--CTA-->
<div class="container py-5">
  <div class="row">
    <div class="col-sm-12 col-md-12 col-lg-6 pb-4">
      <h1 class="display-4 font-weight-bold">Elevate your listening</h1>
      <h5>Everyday headphones that make your favorite artists sound like their performing a never-ending encore.</h5>
    </div>
    <div class="col-sm-12 col-md-12 col-lg-6">
    </div>
  </div>
</div>

Reload the http://127.0.0.1:8000/ page and there should now be some text on the left half of the screen.  To improve the spacing between the CTA and the navbar add py-5 to the division element with the container class attribute.

CTA section with CTA message

 

Add a products button to the CTA section

env > mysite > main > templates > main > home.html

<!--CTA-->
<div class="container py-5">
  <div class="row">
    <div class="col-sm-12 col-md-12 col-lg-6 pb-4">
      <h1 class="display-4 font-weight-bold">Elevate your listening</h1>
      <h5>Everyday headphones that make your favorite artists sound like their performing a never-ending encore.</h5>
      <a class="btn btn-primary mt-2" href="/products">FIND YOUR SET</a>
    </div>
    <div class="col-sm-12 col-md-12 col-lg-6">
    </div>
  </div>
</div>

Now we'll add a blue Bootstrap button that links to the products page. First create an anchor element with a hyperlink right after the heading five element of the CTA section. Then add btn btn-primary and mt-2 to the anchor tag class attribute. Fill in the href with "/products" although this link will not work until we create a products.html template and add a URL path. The reloaded http://127.0.0.1:8000/ page should now look like this:

CTA button








4: Creating a static folder in Django


Now that we added some text let's add an image to the right side column of the CTA. However, before we add the image element to the HTML code, we need to configure our project to load static files. Static signifies the content does not need to be processed or edited before being displayed.

 

Create a static folder

env > mysite > (New Folder) static > (New Folder) img

Create Django static and img foldersGIF

To load images from Django's project folders, the first thing we need is a static folder. Go to the env > mysite folder and create a new folder called static. Within the static folder add another folder named img.

 

Download the static images folder

Download image folderGIF

Download: Tutorial static images folder

Next, we need to find an image.  Download the zipped folder above containing the static photos used in this projectPlace the zipped folder inside the static > img folder.

 

Unzip the static images folder

Unzip static imagesGIF

Open the Windows File Explorer or Mac Finder and unzip the static_images folder. Save the images in the img folder.  Delete the zipped static_images folder once the images are extracted.  Makes sure the images themselves are located in the img folder.

 

Configure settings.py for static images

env > mysite > mysite > settings.py

...

# Application definition

INSTALLED_APPS = [
    'main.apps.MainConfig', 
		...
		...
    'django.contrib.staticfiles',
]

...

Next, we need to go to the mysite settings.py file and make sure 'django.contrib.staticfiles' is listed under INSTALLED_APPS. It should already be listed.

 

...

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/

STATIC_URL = '/static/'

STATICFILES_DIRS = [
   os.path.join(BASE_DIR, "static"),
   ]

Then add the static files directory location to the bottom of the mysite settings.py file after STATIC_URL so the project knows your images are stored in the static folder.  The os.path.join(BASE_DIR, "static") line creates a path to the exact location of the static folder by using the path to the mysite folder known as BASE_DIR.

 

Add an image to the CTA in the home.html

env > mysite > main > templates > main > home.html

<!DOCTYPE html>
<html>
  <head>
    ...
  </head>
  <body>

    {% load static %}

    <!--Navbar-->
    ...

    <!--CTA-->
    ...

    <!-- Optional Javascript -->
    ...
  </body>
</html>

Now let's format the home.html document to read our static files. Go to the home.html page and add the load static tag right before the Navbar comment. Now we can load images via the static tag.

 

<!--CTA-->
<div class="container py-5">
  <div class="row">
    <div class="col-sm-12 col-md-12 col-lg-6 pb-4">
      <h1 class="display-4 font-weight-bold">Elevate your listening</h1>
      <h5>Everyday headphones that make your favorite artists sound like their performing a never-ending encore.</h5>
      <a class="btn btn-primary mt-2" href="/products">FIND YOUR SET</a>
    </div>
    <div class="col-sm-12 col-md-12 col-lg-6">
      <img src="{% static 'img/cta-headphones.jpg' %}" alt="Headphones">
    </div>
  </div>
</div>

Add an image to the right side column of the CTA. First, add the image element to the second column in the HTML code. Then add the image src="{% static "img/cta-headphones.jpg" %}" to the second column of the row we made earlier. Make sure to also add the alternate text attribute "Headphones" describing the image. 

Reload the http://127.0.0.1:8000/ page and there should now be an image of headphones on right side of the screen. But oh no, the image is gigantic!

Large CTA image

 

Resize the CTA image

env > mysite > main > templates > main > home.html

<div class="col-sm-12 col-md-12 col-lg-6">
	<img class="img-fluid rounded" src="{% static 'img/cta-headphones.jpg' %}" alt="Headphones">
</div>

To solve this issue add the Bootstrap class="img-fluid" to the image element so the image responsively scales with the container that holds it. Also add rounded to the class attribute of the image to round the corners.

Updated CTA image






Quiz Questions


1. Where does the static folder belong?


2. Which tag is necessary to load images in an HTML template?


Next lesson


Check out the comments and debug buttons if you get stuck.