Using your own flavor of Bootstrap in a Django project - Part 1

Published byGoogle on

Welcome back for another Django tutorial!
"But why do we need a tutorial for using Bootstrap with Django?" are some going to ask. It's just a matter of downloading it and dropping it in your media directory.
Well, that's true if you want to use an out-of-the-box Bootstrap but in this tutorial we are going to show you how to install Bootstrap inside your project and change it's default appearance.

As in the Starting a Django project and deploying it to an Apache server series, we will be using Mercurial as a revision tool.
We will also be using the project built during that tutorial. If you haven't built that project you can clone it from

Once again, this is our way of doing things, not the only nor the best way of doing them.

Before installing Boostrap, we need to prepare our homepage to be bootstraped. This mean we are going to insert some (decorative) bootstrap-recognized elements inside our page. We'll keep it simple for now, we only need a header, a footer, a left-column with a make-shift profile as well as our pre-existing main content (remember, we are building a Twitter-like project).

To do so, update your babbler/templates/babbler/status_list.html template in the following manner:

{% load staticfiles %}
    <div class="container">
      <header class="navbar navbar-top" role="banner">
        <a href="/" class="navbar-brand">BaBbLeR</a>
        <div class="clearfix"></div>
        <ul class="nav nav-justified">
          <li class="active">Home</li>
          <li><a href="#">Menu item 1</a></li>
          <li><a href="#">Menu item 2</a></li>
          <li><a href="#">Menu item 3</a></li>
          <li><a href="#">Menu item 4</a></li>
      <div class="clearfix"></div>
      <div class="row">
        <div class="col-md-3">
          <div class="nav-right">
            <img src="{% static 'images/me.png'%}" class="pull-left profile-pic"/>
            <p>Hello,<br/>here are a few slices of my life.</p>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse non elit nec tortor aliquet condimentum. Suspendisse euismod nisl orci, sit amet posuere justo tristique ut. Sed porttitor, nisi a imperdiet commodo, neque ante bibendum mi, nec suscipit dolor est a lectus. Donec accumsan sodales rhoncus. Duis congue vehicula metus, nec tempus tellus gravida sed. Praesent feugiat volutpat mauris quis scelerisque. Cras feugiat, lorem eget volutpat consectetur, lorem justo consequat orci, sed tincidunt nisl orci accumsan ante. Ut eu laoreet massa. Sed commodo accumsan ornare. Etiam egestas mollis euismod. Fusce vehicula mauris in est pretium, ac auctor lectus pellentesque. Aliquam et leo rhoncus elit sagittis faucibus. Quisque sit amet neque venenatis lorem placerat sodales sed eu metus. Nullam ut felis id urna iaculis consectetur vitae nec tortor. Mauris bibendum, sem mattis malesuada pretium, lectus libero vestibulum est, pulvinar fringilla purus eros a orci.</p>
        <div class="col-md-9">
          <h1>My moods:</h1>
          {% for object in object_list %}
            <div class="status">
              <span>{{ object.status }}</span>
          {% endfor %}
      <div class="clearfix"></div>
        <p class="pull-right">Usual footer blah</p>

You may download my me.png file (downloaded for free from TurboMilk's LiveJournal icon pack)  and put it inside media/images directory (you will probably have to create it). Or use you own duck-face shot Wink

Now if you go to your homepage, you will see something looking like the picture on the right. It ain't pretty!

To make this a little less ugly, we are going to install Bootstrap. Now Bootstrap source comes in 2 flavors:

We could pick any one of them or even have 2 different versions of this tutorial but since, in a few weeks, we are going to feature a Grappelli admin interface tutorial and that Grappelli uses a Sass-based css, we will also be using the Sass-based version of Bootstrap (no need to disperse).

One thing to know about Sass files is that they need to be compiled. Although there are other ways, I usually use Compass to compile my Sass files. One of the things I like about Compass is that you start it in a separate shell and let it run, it will watch your files for changes and auto-magically recompile everything.

In this case-scenario, Bootstrap can be considered as a library (like South) and in the first series of this tutorial, we have learned to use VirtualEnv but Bootstrap is not a Python library so we can't use VirtualEnv to manage it.
Bootstrap is not a Python library but its Sass version is a Ruby library (and Compass as well).
And to manage libraries in Ruby, there is a tool called Bundler which, while different, will assume the same role as VirtualEnv in our project. If it is not already installed on your development machine, install it now.

When we told you about why it was important to use a tool to manage libraries in a development environment in the Starting a Django project and deploying it to an Apache server serie, we also told you libraries should be handled a different way on production servers. But that's a non-issue regarding those Ruby libraries since they will only be used on the develpment machine in order to output a css file.

The way Bundler works is that it uses a Gemfile file in which it stores a list required libraries, a bit like our requirements.txt file with VirtualEnv, except we can't pick it's name. Optionally Bundler also uses a .bundle/config file but we are not gonna dive into it here.

So in order to start our bundle environment lets create both those files.

source ''

gem 'compass'
gem 'bootstrap-sass', '~> 3.1.1'

.bundle/config (inspired by braincrafted):

BUNDLE_PATH: project_gems/

Now that we created those files it is time to install our Bundle (same as creating a VirtualEnv but with Ruby) and create a Compass project inside our Bundle:

$ bundle install
Fetching gem metadata from
Fetching gem metadata from
Resolving dependencies...
Installing sass (3.2.14) 
Installing bootstrap-sass ( 
Installing chunky_png (1.3.0) 
Installing fssm (0.2.10) 
Installing compass (0.12.2) 
Using bundler (1.3.5) 
Your bundle is complete!
Gems in the group " were not installed.
It was installed into ./project_gems
$ bundle exec compass create . -r bootstrap-sass --using bootstrap
directory ./javascripts/bootstrap/ 
directory ./sass/ 
directory ./stylesheets/ 
directory ./stylesheets/fonts/bootstrap/ 
   create ./config.rb 
   create ./sass/styles.scss 
   create ./sass/_variables.scss 
   create ./javascripts/bootstrap/affix.js 
   create ./javascripts/bootstrap/popover.js 
   create ./javascripts/bootstrap/alert.js 
   create ./javascripts/bootstrap/button.js 
   create ./javascripts/bootstrap/carousel.js 
   create ./javascripts/bootstrap/dropdown.js 
   create ./javascripts/bootstrap/transition.js 
   create ./javascripts/bootstrap/collapse.js 
   create ./javascripts/bootstrap/modal.js 
   create ./javascripts/bootstrap/scrollspy.js 
   create ./javascripts/bootstrap/tooltip.js 
   create ./javascripts/bootstrap/tab.js 
   create ./stylesheets/fonts/bootstrap/glyphicons-halflings-regular.ttf 
   create ./stylesheets/fonts/bootstrap/glyphicons-halflings-regular.svg 
   create ./stylesheets/fonts/bootstrap/glyphicons-halflings-regular.woff 
   create ./stylesheets/fonts/bootstrap/glyphicons-halflings-regular.eot 
   create ./stylesheets/styles.css 

Congratulations! Your compass project has been created.

You may now add and edit sass stylesheets in the sass subdirectory of your project.

Sass files beginning with an underscore are called partials and won't be
compiled to CSS, but they can be imported into other sass stylesheets.

You can configure your project by editing the config.rb configuration file.

You must compile your sass stylesheets into CSS when they change.
This can be done in one of the following ways:
  1. To compile on demand:
     compass compile [path/to/project]
  2. To monitor your project for changes and automatically recompile:
     compass watch [path/to/project]

More Resources:
  * Website:
  * Sass:
  * Community:

To import your new stylesheets add the following lines of HTML (or equivalent) to your webpage:
  <link href="/stylesheets/styles.css" rel="stylesheet" type="text/css" />

Compass just created a project skeleton using Bootstrap which might be nice for a "standalone" css project but which doesn't quite fit our needs for a Django-based project.

Note: There is no need to activate an environment as in VirtualEnv here, were are directly asking Bundler to run the commands for us (bundle exec), so it loads the environment itself before running the requested command.

First, let's edit Compass config file (config.rb) to tell it where we want our files:

require 'bootstrap-sass'
# Require any additional compass plugins here.

# Set this to the root of your project when deployed:
http_path = "/"
## We could have used media/css - This is where Campass will create the css files corresponding to the directory structure in the sass dir
## Setting this in media is just a preparation for the next tutorial series
css_dir = "media"
sass_dir = "sass"
## This is where our images will be located
images_dir = "static/images"
## and our javascripts
javascripts_dir = "static/js"

##Leave the rest of the file untouched for now

You might have noticed the static directory mentioned twice. We are not going to use it directly. In the previous turorial series, we configured STATIC_ROOT as being that static directory, this is where Django will copy media from installed libraries and also from our own MEDIA_ROOT (configured as being the media directory). This is what happens when you run collectstatic. Remember? it is part of our deployment script.

Now let's move the files according to the changes we made inside config.rb and collect everything in the static directory:

$ mkdir sass/css
$ mv sass/*.scss sass/css
$ mv javascripts media/js
$ mv stylesheets/fonts media/
$ rm -rf stylesheets/
$ pyhton collectstatic

Compass also uses a .sass-cache directory for caching purposes, don't forget to add it to your .hgignore file.
Now you may compile our css using the following command (and leaving it running in a separate shell if you are planning on further modifications):

$ bundle exec compass watch
>>> Change detected at 16:17:36 to: css/styles.scss
   create media/css/styles.css 
>>> Compass is watching for changes. Press Ctrl-C to Stop.

And add the following line to the <head> section of your babbler/templates/babbler/status_list.html:

<link href="{% static 'css/styles.css' %}" rel="stylesheet" type="text/css">

Now when you go back to your homepage, you should see something resembling the screenshot on the left, which already looks much better than what we first had.

But we are not there yet, it is still looking very "raw".

Next week, we will see to adding some colors and background gradients by modifying Sass files.
Teaser: Sass is an indented CSS using mixings and variables and it's easier to edit than css (or at least friendlier).

Note: The newly created styles.css has to be added to the repository. You might find that wierd since it is a compiled file but actually it is not: this file is compiled thanks to software only present on the development machine thus has to be deployed "as is" on the production server and since we have been using Mercurial to deploy on the said server, the file needs to be included in the repository

This is were we'll be stopping for this week, I hope to see you again next week for part 2 of this tutorial.
Have a great week!

Bootstrap Sass Compass Tutorial Django


Post a comment