Skip to main content

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

Introduction

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

Objective

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

Assumptions

  • 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

Installation

Step 1 - Configure Django to use MySQL

Open the settings.py file
vim /var/www/html/projects/webapps/webapps/settings.py
Comment or Replace the Database section with the following
DATABASES = {
'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.
    #ServerName www.example.com
        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/wsgi.py
    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
        </Directory>
        # 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
</VirtualHost>

# 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/chartit.py

Step 4 - Create a Django App and call it budget

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

Step 5 - Create a Django Model

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

# Create your models here.
category_choices = (('Housing','Housing'),
                    ('Transportation','Transportation'),
                    ('Personal','Personal'),
                    ('Vacation','Vacation'),
                    ('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/settings.py
Find 'INSTALLED_APPS' and replace it with the following:

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'budget',
    'chartit',
)

Step 7 - Run migrations on your Models

python manage.py makemigrations budget
python manage.py sqlmigrate budget 0001
python manage.py 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 manage.py createsuperuser
Username (leave blank to use 'root'): admin
Email address: admin@admin.com
Password:
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']

admin.site.register(Expense, 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/
mv views.py views.py.bak
vim views.py
Cut and paste the following in views.py
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 = \
        PivotDataPool(
           series=
            [{'options': {
               'source': Expense.objects.all().values(),
               'categories': [‘category_text']},
              'terms': {
                'sum' : Sum('expense_value')}}])

    chart1 = PivotChart(
            datasource = total_per_category_pivot,
            series_options =
              [{'options':{
                  'type': 'column',
                  'stacking': False},
                'terms':[
                  'sum']}],
            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
<head>
    {% 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="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
    <script src="http://code.highcharts.com/highcharts.js" type="text/javascript"></script>
    <script src="/highcharts.js" type="text/javascript"></script>

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

Step 12 - Edit budget url.py file

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

from  budget import views

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

Step 13 - Edit the urls.py file for the project webapps

cd /var/www/html/projects/webapps/webapps/
vim urls.py
Replace the contents of url.py 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(admin.site.urls)),
    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


Comments

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

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 -

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

Introduction I have been using Microsoft Excel to do my Personal Budget. Excel is extremely powerful and has fulfilled my needs. But I always wanted to build a web application which is accessible via a browser and in order to do so we need the following: An admin interface (website) to plug in my expenses A database to store all the entries Code to parse the database and calculate the expenses per month A public interface (website) to display expense charts After browsing the web I stumbled across Django. Django (as copied from the project page) is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. It focuses on automating as much as possible and adhering to the DRY principle. In the first part of this tutorial we will walk through the installation of Django using Virtualenv. In the following series we will build our Personal Budget application using Django. What is virtualenv and why use it? Virtualenv (as copied from th