Skip to main content

Part 2- Install Django using Virtualenv, Apache and MySQL on Ubuntu Server 14.10


In Part 1 of this tutorial we successfully installed Django. In this tutorial we will build our first Django app. We will build a Personal Budget where you will be able to:
  • Enter an expense on a web page
  • View bar graphs of your expenses on a web page


In this tutorial we will:
  • Configure Django to use MySQL
  • Configure Django to use Apache
  • Install and configure django-chartit to display pretty graphs
  • Create our Personal Budget Django App


  • Fresh Install of Ubuntu Server 14.10
  • SSH enabled (sudo apt-get install ssh-server)
  • User has root privileges
  • Basic familiarity with using the Linux command line (terminal)
  • Have completed installation steps outlined in Part 1 of this tutorial


Step 1 - Configure Django to use MySQL

Open the file
vim /var/www/html/projects/webapps/webapps/
Comment or Replace the Database section with the following
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'django',
'USER': 'django',
'PASSWORD': 'django',
'HOST': 'localhost', # Or an IP Address that your DB is hosted on
'PORT': '3306',

Step 2 - Configure Django to use Apache

Take and backup and open the Apache's configuration file
mv /etc/apache2/sites-enabled/000-default.conf /etc/apache2/sites-enabled/000-default.conf.bak
vim /etc/apache2/sites-enabled/000-default.conf
Insert the following configuration
<VirtualHost *:80>
    # The ServerName directive sets the request scheme, hostname and port that
    # the server uses to identify itself. This is used when creating
    # redirection URLs. In the context of virtual hosts, the ServerName
    # specifies what hostname must appear in the request's Host: header to
    # match this virtual host. For the default virtual host (this file) this
    # value is not decisive as it is used as a last resort host regardless.
    # However, you must set it for any further virtual host explicitly.
        WSGIDaemonProcess webapps python-path=/var/www/html/projects/webapps:/var/www/html/projects/lib/python2.7/site-packages
        WSGIProcessGroup webapps
        WSGIScriptAlias / /var/www/html/projects/webapps/webapps/
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html

    Alias /static/ /var/www/html/projects/local/lib/python2.7/site-packages/django/contrib/admin/static/
        <Directory /var/www/html/projects/local/lib/python2.7/site-packages/django/contrib/admin/static/>
            Require all granted
        # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
    # error, crit, alert, emerg.
    # It is also possible to configure the loglevel for particular
    # modules, e.g.
    #LogLevel info ssl:warn

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    # For most configuration files from conf-available/, which are
    # enabled or disabled at a global level, it is possible to
    # include a line for only one particular virtual host. For example the
    # following line enables the CGI configuration for this host only
    # after it has been globally disabled with "a2disconf".
    #Include conf-available/serve-cgi-bin.conf

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet
Restart Apache
service apache2 restart
Open your browser and Navigate to your servers URL (http://your-server-ip). The Django webpage should be displayed

Step 3 - Install and configure Chartit

cd /var/www/html/projects/
. bin/activate
pip install django-chartit
pip install simplejson
cd /var/www/html/projects/local/lib/python2.7/site-packages/django/contrib/admin/static/
cp -R /var/www/html/projects/local/lib/python2.7/site-packages/chartit/static/chartit/ .
Find and Replace 'from django.utils import simplejson' with 'import simplejson' in the following file
vim /var/www/html/projects/lib/python2.7/site-packages/chartit/templatetags/

Step 4 - Create a Django App and call it budget

cd /var/www/html/projects/
. bin/activate
cd webapps/
python startapp budget

Step 5 - Create a Django Model

Edit the following file
vim /var/www/html/projects/webapps/budget/
Delete the contents and insert the following:
from django.db import models

# Create your models here.
category_choices = (('Housing','Housing'),
                    ('Savings', 'Savings'))

class Expense(models.Model):
    expense_date = models.DateField('date published')
    category_text = models.CharField(choices=category_choices,max_length=50)
    description_text = models.CharField(max_length=200)
    expense_value = models.DecimalField(default=0, max_digits=10, decimal_places=2)

We have done the following:
  • Created categories for our expenses like Housing, Transportation etc.
  • Created various database fields. When we enter expenses we will have the ability to:
    • Enter a date for the expense
    • Choose a category for the expense
    • Provide a description for the expense
    • Enter the expense value

Step 6 - Enable our newly created app (budget) and installed app (chartit)

Edit the following file
vim /var/www/html/projects/webapps/webapps/
Find 'INSTALLED_APPS' and replace it with the following:


Step 7 - Run migrations on your Models

python makemigrations budget
python sqlmigrate budget 0001
python migrate

Step 8 - Create an Admin account

(projects)root@django:/var/www/html/projects/webapps# cd /var/www/html/projects/
(projects)root@django:/var/www/html/projects/webapps# python createsuperuser
Username (leave blank to use 'root'): admin
Email address:
Password (again):
Superuser created successfully.
Navigate to the server http://your-server-ip/admin. Enter your credentials and verify you can access the admin console.

Step 9 - Add our app to the Admin site

from django.contrib import admin
from budget.models import Expense

class ExpenseAdmin(admin.ModelAdmin):
    fields = ['expense_date', 'category_text', 'description_text', 'expense_value']
    list_display = ('expense_date', 'category_text', 'description_text', 'expense_value')
    list_filter = ['category_text']
    search_fields = ['description_text', 'expense_value'], ExpenseAdmin)
Restart Apache

service apache2 restart
Navigate to the Admin site. There should be an option to add expenses. Add a few expenses

Step 10 - Create a Django Views to display the expense graphs

cd /var/www/html/projects/webapps/budget/
Cut and paste the following in
from django.shortcuts import render, render_to_response
from django.db.models import *

# Create your views here.
from chartit import DataPool, Chart, PivotDataPool, PivotChart
from budget.models import *

#Create a data  source  
    total_per_category_pivot = \
            [{'options': {
               'source': Expense.objects.all().values(),
               'categories': [‘category_text']},
              'terms': {
                'sum' : Sum('expense_value')}}])

    chart1 = PivotChart(
            datasource = total_per_category_pivot,
            series_options =
                  'type': 'column',
                  'stacking': False},
            chart_options =
              {'title': {
                   'text': 'Total Expenditure per Category'},
               'xAxis': {
                    'title': {
                       'text': 'Categories'}}})

    #Step 3: Send the chart object to the template.
    return render(request, 'budget/index.html',{'totalpermonth': [chart1]})

Step 11 - Create a Web Template to display the graphs

cd /var/www/html/projects/webapps/budget/
mkdir templates
cd templates
mkdir budget
cd budget
vim index.html
    {% load staticfiles %}
    <!-- code to include the highcharts and jQuery libraries goes here -->
    <!-- load_charts filter takes a comma-separated list of id's where -->
    <!-- the charts need to be rendered to                             -->
    <script src="" type="text/javascript"></script>
    <script src="" type="text/javascript"></script>
    <script src="/highcharts.js" type="text/javascript"></script>

    {% load chartit %}
    {{ totalpermonth|load_charts:"chart1" }}
    <div id="chart1">
 Chart will be rendered here </div>

Step 12 - Edit budget file

cd /var/www/html/projects/webapps/budget/
Replace the contents of file with the following
from django.conf.urls import patterns, url

from  budget import views

urlpatterns = patterns('',
    url(r'^$',, name='total'),

Step 13 - Edit the file for the project webapps

cd /var/www/html/projects/webapps/webapps/
Replace the contents of file with the following
from django.conf.urls import patterns, include, url
from django.contrib import admin

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'webapps.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),

    url(r'^admin/', include(,
    url(r'^total/', include('budget.urls')),

Restart Apache and check out the fancy bar graph

service apache2 restart
Navigate to http://your-server-ip/total and you should see a graph load as long as your server can communicate over the Internet with highcharts and javascript web servers


Popular posts from this blog

Run your Meteor App on a Production Ubuntu 16.04 Server with Nginx

Introduction Meteor enables developers to create apps and quickly test them on a development webserver. Once you have created your app the big question is how to run it on a production server. In this tutorial we will demostrate how to run your Meteor app on Ubuntu 16.04 using Nginx Credits and Acknowledgements This entire post is based off this Digital Ocean article. The article was modified for issues we encountered and adapted for Ubuntu 16.04. The entire credit goes to Daniel Speichert Objective In this tutorial we will: Install and Configure Nginx with HTTPS enabled Install MongoDB Install NodeJS Bundle your Meteor App Create a startup script to automatically start your app on reboot Assumptions We assumue the following: You already have a fresh install of Ubuntu 16.04 Server SSH enabled on your fresh install You have root privelages on your server You have a different server where you can insall meteor and budle your app

Traefik Install and configuration - Part 1

Introduction In this tutorial we are going to install and configure Traefik Proxy . As quoted on their website "Traefik is a leading modern reverse proxy and load balancer that makes deploying microservices easy. Traefik integrates with your existing infrastructure components and configures itself automatically and dynamically." All our applications will be front-ended by traefik. Objective The core objective for this tutorial is to: Configure an A record in our DNS server (pfsesne firewall) to point to our traefik proxy Configure and install Traefik in docker Configure and install two http based applications ( homer and heimdall ) in docker that will be accessed via traefik Topology The above image represents our topology. Our pfsense firewall is connected directly to the Internet and is NAT'ing all traffic from the internal network to the outside world. We have a single LAN segment ( defined on pfsense and we have the following two PC's connected d

Installing Zurmo on Ubuntu Sever 14.10

Introduction Zurmo is an Open Source Customer Relationship Management (CRM) application that is mobile, social, and gamified. It can be used to: Create and Track Project progress Create Customer Accounts Tasks - Associate Tasks to Accounts and/or Projects Customize fields of Tasks, Accounts etc. Generate Reports etc. Objective The final objective is to install Zurmo 2.8.5 on Ubuntu Server 14.10 Assumptions Fresh Install of Ubuntu Server 14.10 SSH enabled (sudo apt-get install ssh-server) User has sudo or root privileges Step 1: Install the Apache Webserver sudo apt-get install apache2 -y Step 2: Install MySQL Server sudo apt-get install mysql-server -y Step 3: Install PHP5 sudo apt-get install php5 -y sudo apt-get install php5-mysql -y sudo apt-get install php5-memcache -y sudo apt-get install php5-curl -y sudo apt-get install php-apc -y sudo apt-get install php-soap -y sudo apt-get install php5-imap -