Roshan Book

My Tech Notebook

Category Archives: Python web development

Django Deployment Guide For Ubuntu


Ignite your Django projects with nginx, Apache and mod_wsgi

There’s a time when every Django developer has to think about deployment scenarios, when I first did it last year I thought that a setup involving Lighty, Apache, mod_proxy and mod_python was a good choice but my first approach was not the best. I put Apache as the front server, handling requests for Django generated pages and passing, via mod_proxy, requests for static content to Lighty on the back. A setup where Apache had to work even for files that wasn’t supposed to serve was a very bad idea.

After many helpful comments and some more reading I realized that it was better having the server for static content on the front and Apache, which still talks to Django, on the back.

I replaced Lighty with nginx, which according to many seems to be more stable, and opted for mod_wsgi instead of mod_python to make Apache talk to Django. mod_wsgi has a lower memory overhead and it’s suitable for high performance sites. There’s no need for mod_proxy on Apache anymore as nginx is the one in charge of the proxy work now.

This is an easy to follow and very focused guide for developers who know how to handle their servers so I won’t consider security issues, memcached, Django installation, databases or basic GNU/Linux, Apache and DNS settings. Of course all of those subjects are important and you should take care of them.

The plan

This guide includes all the steps needed to:

  • Setup a domain for your Django project.
  • Create a simple directory layout for Django sites.
  • Configure Apache with mod_wsgi for Django.
  • Configure nginx.
  • Serve Django admin media files.
  • Turn on the heat and show your greatest and latest Django stuff to the world.

After following all the steps you will have a Django site running with nginx on the front and Apache on the back. nginx will manage all static content and will pass Django requests to Apache and mod_wsgi.

I have tested on three Ubuntu servers (two running 8.10, Intrepid Ibex, and one 7.10, Gutsy Gibbon) but everything should be pretty similar in other GNU/Linux distributions.

Shall we start?

Setup a domain for your Django project

Many of us run more than one website in one server, I have several with Drupal and a few with Django living in one box, so let’s consider a two domains scenario: will host the Django project anything else. Most of the work will focus in, I just mention to give you some context. Obviously you should replace all the domain names in this guide with yours.

We’ll use a couple of private IP addresses for now and will replace them with public ones and setup in a DNS server when going live. For this guide I’ll just add to /etc/hosts, which is what I usually do in my development environment:

I’m using and two ports, 80 and 8080, for serving the Django site at The default port 80 will be used by nginx to serve static content and Django will look for files under the /media directory. Port 8080 will be used by Apache to handle Django requests.

Create a simple directory layout for Django sites

Directory layouts depend on personal preferences, I currently use a /home/alexis/djcode directory for all my Django coding and the new project will be called cataybea; hence, we have to run:

mkdir /home/alexis/djcode cd /home/alexis/djcode/ startproject cataybea

Now let’s create some additional directories:

mkdir /home/alexis/djcode/cataybea/apache mkdir /home/alexis/djcode/cataybea/logs mkdir /home/alexis/djcode/cataybea/media

What are they for? apache will contain a Python script to setup mod_wsgi, logs will store Apache and nginx logs and media is the directory nginx will use to serve static files for our Django project.

You can later manage the whole /home/alexis/djcode/cataybea directory with your favorite version control tool.

Take note of the correct paths for using later in the configuration files.

Configure Apache with mod_wsgi for Django

I assume you already have Apache working correctly and just need to tweak a little for our Django setup. As we’ll be running two web servers at once we must make sure that IP addresses and ports won’t conflict. Let’s edit /etc/apache2/ports.conf:

Listen Listen #Listen 80

I have specified IP addresses and ports to listen. Notice I commented the default Listen 80 as it means Apache would listen to that port in all IP addresses. If you want to use SSL take care of the 443 port in the same way.

If you are using virtual hosts in Apache confirm it’s listening to the correct IP addresses and ports, I have this in/etc/apache2/sites-enabled/


Restart Apache and make sure your Apache sites work normally. I’m obsessed with testing at every step in the way and I suggest you are too.

sudo /etc/init.d/apache2 restart

Now it’s time to add mod_wsgi to Apache. The latest versions of Ubuntu have it in the repository:

sudo apt-get install libapache2-mod-wsgi

For older versions of Ubuntu, such as Gutsy, you need to find the .deb file and use something like dpkg -i to install.

Now it’s time to create the Apache configuration file for in /etc/apache2/sites-available/

<VirtualHost> ServerAdmin ServerName ServerAlias <Directory /home/alexis/djcode/cataybea/apache/> Order deny,allow Allow from all </Directory> LogLevel warn ErrorLog /home/alexis/djcode/cataybea/logs/apache_error.log CustomLog /home/alexis/djcode/cataybea/logs/apache_access.log combined WSGIDaemonProcess user=www-data group=www-data threads=25 WSGIProcessGroup WSGIScriptAlias / /home/alexis/djcode/cataybea/apache/cataybea.wsgi </VirtualHost>

Notice the IP address and port: This site won’t be accessed directly but via proxy from nginx. We’ll set that up in the next section.

Now we need a Python script to configure our Django project to use mod_wsgi, create/home/alexis/djcode/cataybea/apache/cataybea.wsgi and put the following code inside:

import os, sys apache_configuration= os.path.dirname(__file__) project = os.path.dirname(apache_configuration) workspace = os.path.dirname(project) sys.path.append(workspace) sys.path.append(‘/usr/lib/python2.5/site-packages/django/’) sys.path.append(‘/home/alexis/djcode/cataybea’) os.environ[‘DJANGO_SETTINGS_MODULE’] = ‘cataybea.settings’ import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler()

Don’t restart Apache yet as we need to complete a few more steps.

Configure nginx

nginx will do two things: serve static content from and pass all other requests to Apache. Let’s install it first:

sudo apt-get install nginx

Now remove the nginx default site:

sudo rm /etc/nginx/sites-enabled/default

Apache and nginx should be using the same user, for Ubuntu this is www-data, and your /etc/nginx/nginx.confshould look like this:

user www-data; worker_processes 2; error_log /var/log/nginx/error.log; pid /var/run/; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; access_log /var/log/nginx/access.log; sendfile on; tcp_nopush on; keepalive_timeout 65; tcp_nodelay on; gzip on; include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; }

worker_processes can be set to the number of cores in your server, in my case that’s just 2.

Configure a the site on nginx by creating /etc/nginx/sites-available/

server { listen; server_name; access_log /home/alexis/djcode/cataybea/logs/nginx_access.log; error_log /home/alexis/djcode/cataybea/logs/nginx_error.log; location / { proxy_pass; include /etc/nginx/proxy.conf; } location /media/ { root /home/alexis/djcode/cataybea/; } }

then running:

sudo ln -s /etc/nginx/sites-available/ /etc/nginx/sites-enabled/

and finally creating the file that will take care of proxying Django requests to Apache, we’ll call it/etc/nginx/proxy.conf and put this inside:

proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; client_max_body_size 10m; client_body_buffer_size 128k; proxy_connect_timeout 90; proxy_send_timeout 90; proxy_read_timeout 90; proxy_buffer_size 4k; proxy_buffers 4 32k; proxy_busy_buffers_size 64k; proxy_temp_file_write_size 64k;

Notice $host, $remote_addr and $proxy_add_x_forwarded_for are variables that will be handled by nginx, you don’t need to change anything else in proxy.conf for a basic setup. When I started playing with nginx I thought these had to be replaced by me, I was wrong.

Finally restart nginx:

sudo /etc/init.d/nginx restart

and Apache:

sudo /etc/init.d/apache2 restart

That should be it! If you visit you should see some Django content (could be the welcome page, some of your views or a 404 page depending on your project status). To try the nginx media server create a test.htm file with some dummy content in /home/alexis/djcode/cataybea/media and visit

Serve Django admin media files (optional)

If you will use the Django admin application edit /home/alexis/djcode/cataybea/, make sure your database settings are correct, add ‘django.contrib.admin’ to the INSTALLED_APPS tuple and change theADMIN_MEDIA_PREFIX like this:

ADMIN_MEDIA_PREFIX = ‘/media/admin/’

Let’s enable the admin url by editing /home/alexis/djcode/cataybea/, uncommenting these two lines:

from django.contrib import admin admin.autodiscover()

and adding this to urlpatterns:

(r’^admin/’, include(,

Now let’s create a symbolic link to the media files for the Django’s administration section:

cd /home/alexis/djcode/cataybea/media ln -s /usr/lib/python2.5/site-packages/django/contrib/admin/media/ admin

And finally let’s create the administration user and the required tables in the database:

cd /home/alexis/djcode/cataybea/media python syncdb

As with every other modifications in your Django code you will have to reload Apache for changes to take effect:

sudo /etc/init.d/apache2 reload

Visit,including the trailing slash, and you should be in business.

How to install MySQLdb in a virtualenv on Ubuntu Karmic

Source :

Install dependencies
sudo apt-get build-dep python-mysqldb
Install MySQLdb with pip/virtualenv
cd ~/lib/python-environments
virtualenv –distribute –no-site-packages default
pip install -E default/ MySQL-python

Django email setup on Hostgator

Originally published at
On Hostgator it is possible to run Django applications with FastCgi, but it has only sendmail as email back-end which is not included in Django.

Hopefully there is a snipets to resolve this limitation. You just needed to change the path of the sendmail file and it was ready to run. The location of sendmail is “/usr/sbin/sendmail” on our Hostgator server.

And the email backend should be configured in your by adding the following line:

EMAIL_BACKEND = ‘sendmail.EmailBackend’

Setting up rancho in django

Follow instructions listed in here

Installing psycopg2 :

Installing mysqldb –

to install dependencies inside virtual env:

install virtuaev -pip install virtualenv
install python image library-
pip install --no-index -f -U PIL
install mysqldb- pip install MySQL-python
install pytz - pip install pytz
install pisa - pip install pisa

Go to wikiboard view change ho.pisa module to xhtml2pdf.pisa

add ’django.middleware.csrf.CsrfResponseMiddleware’, to settings

add mysql only as database setting

install all rancho needed module via sudo easy_install modulename

When you implement the project you get an error where you are unable to upload and message under any project. To solve this refer

Patch is at


To resolve tinymce>> error – cannot import smart_unicode

see patch

Django revision 2

Dictionaries,tuple and lists

Setting up templates

1. Create templates folder in root of your project

2. Add this code to top of

import os.path

3. Go to TEMPLATE_DIRS = ( and add

os.path.join(os.path.dirname(__file__), ‘templates’ ),

That is it

Setting up css, js

1. Create a folder static in root of project

2. To Media root and Media url add

MEDIA_ROOT = os.path.join(DIRNAME,’static/’)

MEDIA_URL = ‘/static/’

3. Go to

4. To the top add – import os and then –  static=os.path.join(os.path.dirname(__file__),’static’)

5. To urlpatterns = patterns(”, add

(r’^static/(?P<path>.*)$’, ‘django.views.static.serve’,{‘document_root’: static}),

That is it

You can refer to them in templates as you do normally like

<link rel=”stylesheet” type=”text/css”
href=”/static/css/style.css” />

* Add following code to your model def to see values by name

def __unicode__(self):

Few useful Notes

Start a project : startproject mysite

Running a server :python runserver 8080

Sync database :python syncdb

Creating an app -python startapp polls

Add a app to – below installed app ‘projectname.appname’

Add a middleware class to enable login logout functionality out of the box -‘django.middleware.csrf.CsrfResponseMiddleware’,

Looking at sql :python sql polls

Running a python shell :python shell

Inside shell looking at attributes of user class

@login_required – to save a view to login required. Add from django.contrib.auth.decorators import login_required – to top of

>>from django.contrib.auth.models import User


Few useful reference charts
Regular Expression

Models Field Type 
Available Formfieldtypes and Widgets 

Additonal parameters forformfieldtypes

Create folder by name

modifying admin view

DataEntry via shell

Look at :

Form to database


call the class into views

refer to a template

Rendering the form:

3 types:

This command will give you a long output in which you will see the HTML
rendering of the form using table tags. You can also render the form using ul
and p tags by calling form.as_ul() and form.as_p() respectively.

Creating a form inside

from django import forms
import re
from django.contrib.auth.models import User

class RegistrationForm(forms.Form):
username=forms.CharField(label=u’Username’, max_length=30)
password1=forms.CharField(label=u’Password’, widget=forms.PasswordInput())
password2=forms.CharField(label=u’Password (Again)’,widget=

Templates notes

1. Create base.html in template directory

2. To the next template include base.html by using -{% extends “base.html” %}

3. In base.html use blocks like – {% block title %}{% endblock %}

4. In next template override this block as {% block title %}Welcome to B2wPms{% endblock %}

5. Call a database variable inside template as – Welcome {{project. user.username }}

6. calling a form inside template

<form method=”post” action=”.”>
{{ form.as_p }}
<input type=”submit” value=”save” />

include tag – {% include “bookmark_list.html” %}

Database to table

Direct to template concept

Datamodel relationships – view this

Decoupling Django app

Copy the file mysite/ to polls/ Then, change mysite/ to remove the poll-specific URLs and insert aninclude(), leaving you with:

# This also imports the include function
from django.conf.urls.defaults import *

from django.contrib import admin

urlpatterns = patterns('',
    url(r'^polls/', include('polls.urls')),
    url(r'^admin/', include(,

include() simply references another URLconf. Note that the regular expression doesn’t have a $ (end-of-string match character) but has the trailing slash. Whenever Django encounters include(), it chops off whatever part of the URL matched up to that point and sends the remaining string to the included URLconf for further processing.


Enabling admin interface

  • Add "django.contrib.admin" to your INSTALLED_APPS setting.
  • Run python syncdb. Since you have added a new application to INSTALLED_APPS, the database tables need to be updated.
  • Edit your mysite/ file and uncomment the lines that reference the admin – there are three lines in total to uncomment. This file is a URLconf; we’ll dig into URLconfs in the next tutorial. For now, all you need to know is that it maps URL roots to applications. In the end, you should have a file that looks like this:
    from django.conf.urls.defaults import patterns, include, url
    # Uncomment the next two lines to enable the admin:
    from django.contrib import admin
    urlpatterns = patterns('',
        # Examples:
        # url(r'^$', 'mysite.views.home', name='home'),
        # url(r'^mysite/', include('')),
        # Uncomment the admin/doc line below to enable admin documentation:
        # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
        # Uncomment the next line to enable the admin:
        url(r'^admin/', include(,

    (The bold lines are the ones that needed to be uncommented.)


    Create in apps folder : 

    And add following codes :

    from django.contrib import admin
    from bookmarks.models import *

    class LinkAdmin(admin.ModelAdmin):
    list_display = (‘title’, ‘link’, ‘user’)

    list_filter = (‘user’,)

    ordering = (‘title’,)
    search_fields = (‘title’,), LinkAdmin)

    Do this for all the models for which you want to enable admin features.

    Customizing Admin interface

    Go to /usr/lib/pythonX.X/site-packages/django

    These files are important:

    admin/base_site.html: This is the base template for the administration interface. All the pages inherit from this template.

    admin/change_list.html: This template generates a list of available objects in a particular model.

    admin/change_form.html: This template generates a form for adding or editing an object.

    admin/delete_confirmation.html: This template generates the confirmation page when deleting an object.

Creating User auth system outside

Installing Django on Ubuntu -worked for me

Original post at : sudo ln -s /usr/share/django/django /usr/lib/python2.7/dist-packages/django

I’ve been toying around with some small ideas for websites, and I’ve been looking for some straightforward frameworks that would allow me to quickly prototype a site that could still be used, at least for moderate levels of traffic, in a production environment.  I decided to check out Django, a Python based web framework that supports a lot of out-of-the-box functionality and is easily extensible.

This post outlines the steps I took to install Django on test web server, which is currently running Ubuntu 10.10 (Maverick Meerkat).


As is often the case, I like to configure my test system so that it is as close as possible to the production environment I eventually deploy to.  In many cases, that means deviating from Ubuntu’s distribution repositories and installing some packages from source.  In the case of Django, there is an appliance version of Ubuntu that supports Django, but nothing official in the repositories.  So as usual, I’m back to installing my own version.  Before I started, I laid out a few of the requirements I would like to achieve.

  • Use the latest stable version of Django (1.2.3)
  • Install Django in a shared location, but Django sites should be independent.
  • Each Django site should be in its own Apache VirtualHost, so as not to disturb the other sites I have running on my test server.
  • Each Django site should be easily maintained in source control and should not include any major artifacts from the Django library.  This will make the application portable, and will be helpful when I move it to other servers, such as production.

I based most of my work on an article on,  but made some adjustments along the way to suit my needs, so I’m posting my steps for anyone else that might be following the same path.

Conceptually, you can break down installing Django into the following steps:

  1. Retrieve and Install Django
  2. Create and Configure a Django project
  3. Configure Apache
  4. Get coding on your new Django installation

Retrieve and Install Django

In order to retrieve and install Django, I directly checked out the stable branch from Django’s SVN repository.  I put it in my /usr/share directory, as it is a shared library used by the system.  In addition to checking out the library, I set permissions so that it was owned by the www-data user (my apache user) and linked the Django package into my python library.  I also linked the script into my bin directory so that it is always available on the path.  The steps for doing this are illustrated below.

1 # check out version 1.2.3 of Django into my /usr/share directory and update permissions
3 sudo chown -R www-data:www-data /usr/share/django
5 # link Django package into the python library
6 sudo ln -s /usr/share/django/django /usr/lib/python2.6/dist-packages/django
8 # make available on the path
9 sudo ln -s /usr/share/django/django/bin/ /usr/local/bin/

If you are unsure of where Python is installed on your system, you can get this by running the following line.

1 python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()"

That’s all that’s needed.  You’re now ready to move on to creating your first Django project.

Create and Configure a Django project

Set up the Database

Before you start, you should set up a database for Django to use.  I use MySql, but there are a number of compatible databases and non-database backends that can be used with Django.  My database setup is pretty simple.  Just log into mysql as root

1 mysql -u root - p

and then run the following commands

2 CREATE USER 'mydjango'@'localhost' IDENTIFIED BY 'mydjango'
3 CREATE USER 'mydjango'@'%' IDENTIFIED BY 'mydjango'
4 GRANT ALL PRIVILEGES ON mydjango.* to 'mydjango'@'%' WITH GRANT OPTION;
5 GRANT ALL PRIVILEGES ON mydjango.* to 'mydjango'@'localhost' WITH GRANT OPTION;

Creating the Django Site

Next up is creating the Django site.  Django provides an admin script for creating the project for you, so I only had to choose a directory for where the site would live, and set up the directory structure that I wanted to use.

For my purposes, I wanted my site to live under /var/www, but still be owned by me.  This would allow me eventually to check the site directory under /var/www directly into SVN.  That way, on my test system, I can work directly on the files on the server and check in changes directly to SVN.  Additionally, I can work remotely, and synch the latest changes onto the test server easily via an SVN up.

The directory structure I chose was a follows:

  • /var/www/mydjango
    • django_projects – The directory I will create my projects in.  Using this model, my site can actually be made up of multiple django projects if needed.
    • django_templates – A directory of templates that all Django projects in my site will use.
    • media – A directory where common media (jpgs, gifs, pngs, etc.) will be stored.  These eventually will be accessed outside of the Django framework to reduce overhead.
    • admin_media – A directory that is actually a symbolic link back to the admin_media directory in the main Django library.  This allows the auto-generated admin module to use its resources.

The steps I followed for setting this up were

01 #create directories
02 sudo mkdir /var/www/mydjango/django_projects
03 sudo mkdir /var/www/mydjango/django_templates
04 sudo mkdir /var/www/mydjango/media
06 #link in the admin media
07 sudo ln -s /usr/share/django/django/contrib/admin/media /var/www/mydjango/admin_media
09 #set up ownership so I own the directory.  Make sure www-data still has rx access via group permissions
10 sudo chown -R tom:tom /var/www/mydjango

The next step is to create a new django project.  Django comes with a script (which I’ve already added to the path) that allows you to easily setup a project.  This is just a two-liner, switch to right directory and create the project.

1 cd /var/www/mydjango/django_projects
2 startproject mydjango

Configuring Django

With the script all our files have been created, the next step is to configure Django. First you will modify the /var/www/mydjango/django_projects/mydjango/ file. I’ve included my file below, but the key areas you want to modify are:

  • Add yourself in the ADMINS section
  • Add the correct database to the DATABASES section (my example shows mysql)
  • Set the TIME_ZONE for your server
  • Change MEDIA_ROOT to be the location on disk where your media will reside (the media directory we set up before)
  • Change MEDIA_URL to be the URL where media will be accessed from.
  • Change ADMIN_MEDIA_PREFIX to be the relative URL from the site root where the admin media will be accessed from.
  • Update the SECRET_KEY to something random (this is to randomize any hash and crypto functions for security purposes)
  • Update ROOT_URLCONF to reference the file in your project directory.
  • Add your templates directory (the one created earlier) to the TEMPLATE_DIRS list
  • Enable the admin interface in INSTALLED_APPS by uncommenting ‘django.contrib.admin’

My final is shown below for reference.

01 # Django settings for mydjango project.
03 DEBUG = True
06 ADMINS = (
07     ('TomS', ''),
08 )
13     'default': {
14         'ENGINE': 'mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
15         'NAME': 'mydjango',                      # Or path to database file if using sqlite3.
16         'USER': 'mydjango',                      # Not used with sqlite3.
17         'PASSWORD': 'mydjango',                  # Not used with sqlite3.
18         'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
19         'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
20     }
21 }
23 # Local time zone for this installation. Choices can be found here:
25 # although not all choices may be available on all operating systems.
26 # On Unix systems, a value of None will cause Django to use the same
27 # timezone as the operating system.
28 # If running in a Windows environment this must be set to the same as your
29 # system time zone.
30 TIME_ZONE = 'America/NewYork'
32 # Language code for this installation. All choices can be found here:
34 LANGUAGE_CODE = 'en-us'
36 SITE_ID = 1
38 # If you set this to False, Django will make some optimizations so as not
39 # to load the internationalization machinery.
40 USE_I18N = True
42 # If you set this to False, Django will not format dates, numbers and
43 # calendars according to the current locale
44 USE_L10N = True
46 # Absolute path to the directory that holds media.
47 # Example: "/home/media/"
48 MEDIA_ROOT = '/var/www/mydjango/media/'
50 # URL that handles the media served from MEDIA_ROOT. Make sure to use a
51 # trailing slash if there is a path component (optional in other cases).
55 # URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
56 # trailing slash.
57 # Examples: "", "/media/".
58 ADMIN_MEDIA_PREFIX = '/admin_media/'
60 # Make this unique, and don't share it with anybody.
61 SECRET_KEY = 'hg=dyltl9)pq$4n+aabdd&+6o1yf3ipg1@@8wm(a9-e!ype&d2'
63 # List of callables that know how to import templates from various sources.
65     'django.template.loaders.filesystem.Loader',
66     'django.template.loaders.app_directories.Loader',
67 #     'django.template.loaders.eggs.Loader',
68 )
71     'django.middleware.common.CommonMiddleware',
72     'django.contrib.sessions.middleware.SessionMiddleware',
73     'django.middleware.csrf.CsrfViewMiddleware',
74     'django.contrib.auth.middleware.AuthenticationMiddleware',
75     'django.contrib.messages.middleware.MessageMiddleware',
76 )
78 ROOT_URLCONF = 'mydjango.urls'
81     # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
82     # Always use forward slashes, even on Windows.
83     # Don't forget to use absolute paths, not relative paths.
84     "var/www/mydjango/django_templates/"
85 )
88     'django.contrib.auth',
89     'django.contrib.contenttypes',
90     'django.contrib.sessions',
91     'django.contrib.sites',
92     'django.contrib.messages',
93     # Uncomment the next line to enable the admin:
94     'django.contrib.admin',
95     # Uncomment the next line to enable admin documentation:
96     # 'django.contrib.admindocs',
97 )

You’ll also want to update your to enable the admin urls. Update your /var/www/mydjango/django_projects/mydjango/ to match the file I have below. The updates I made were to uncomment lines 4,5 and 15.

01 from django.conf.urls.defaults import *
03 # Uncomment the next two lines to enable the admin:
04 from django.contrib import admin
05 admin.autodiscover()
07 urlpatterns = patterns('',
08     # Example:
09     # (r'^mydjango/', include('')),
11     # Uncomment the admin/doc line below to enable admin documentation:
12     # (r'^admin/doc/', include('django.contrib.admindocs.urls')),
14     # Uncomment the next line to enable the admin:
15     (r'^admin/', include(,
16 )

The final step in configuring Django is to have Django auto-build your database to match all the default models that come with Django (users, groups, etc.). Django provides a management script that makes this exceedingly easly.

1 cd /var/www/mydjango/django_projects/mydjango/
2 ./ syncdb

Configuring Apache

The final step is to configure Apache.  As I mentioned previously, I wanted everything in a VirtualHost so as not to disturb the other web applications I have running on my test machine.  To do this, I created a new site descriptor as /etc/apache2/sites-available/mydjango.mydomain.home.  Some key setup notes to be aware of are below.  Everything else is pretty standard for an Apache vhost.

  • The <location “/”> element is used to set python and specifically Django as the handler for all requests.  Note that I’m adding the location of my site to the PythonPath and I’m setting the path to my settings file as part of the environment.
  • The alias and additional <location> elements are used to overrie Django and allow Apache to server up the files directly.  The aliases are set up point to the directories created earlier for the Django site

My final configuration file is shown below.

01 <VirtualHost *>
03         RewriteEngine On
05         ServerAdmin
07         ServerName mydjango.mydomain.home
09         #set up Django as the default handler for the site
10         <location "/">
11             SetHandler python-program
13             PythonHandler django.core.handlers.modpython
15             SetEnv DJANGO_SETTINGS_MODULE mydjango.settings
17             PythonPath "['/var/www/mydjango/django_projects'] + sys.path"
18         </location>
20         Alias /media /var/www/mydjango/media
21         <location "/media">
22             SetHandler None
23         </location>
25         Alias /admin_media /var/www/mydjango/admin_media
26         <location "/admin_media">
27             SetHandler None
28         </location>
30         <locationmatch ".(jpg|gif|png)">
31             SetHandler None
32         </locationmatch>
34         ErrorLog /var/log/apache2/mydjango.mydomain.home-error.log
35         # Possible values include: debug, info, notice, warn, error, crit,
36         # alert, emerg.
37         LogLevel warn
38         CustomLog /var/log/apache2/mydjango.mydomain.home-access.log combined
40 </VirtualHost>

After that, I made sure that my domain name was correctly set up on my local DNS server (or you can use a local hosts file), then I enabled the site and reloaded Apache.

1 sudo a2ensite mydjango.mydomain.home
2 sudo /etc/init.d/apache2 reload

I then navigated to http://mydjango.mydomain.home. I immediately got the 404 page you see below, which means that Django is working, I just haven’t set up any views yet.

Django 404 PageDjango is up and working, serving up a 404 page.

As a secondary test, I also went to http://mydjango.mydomain.home which showed the admin login screen below.

Django Admin LoginDjango Admin module is also working

And that pretty much wraps it up.  Django is up and running and ready for development.  I’ll be giving Django a test drive.  If things go well, there will likely be some more blog posts on the topic soon.

Setting up heroku with django and python

Revision before creating an app

How Django process your request


Starting your project – startproject mysite

Running sever – python runserver 8080

Sync Db – python syncdb

Set up database type in

Starting an app– python startapp polls

Add app to under “installed app”

A Sample model to revise :

from django.db import models

class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
     def __unicode__(self):
        return self.question

class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice = models.CharField(max_length=200)
    votes = models.IntegerField()
    def __unicode__(self):
        return self.question
Sync db - python syncdb
See the sql -python sql polls
Getting into your app shell : python shell
InSide shell:
from polls.models import Poll, Choice
For more command visit here
Activating the admin site

Activate the admin site

The Django admin site is not activated by default – it’s an opt-in thing. To activate the admin site for your installation, do these three things:

  • Add "django.contrib.admin" to your INSTALLED_APPS setting.
  • Run python syncdb. Since you have added a new application toINSTALLED_APPS, the database tables need to be updated.
  • Edit your mysite/ file and uncomment the lines that reference the admin – there are three lines in total to uncomment. This file is a URLconf; we’ll dig into URLconfs in the next tutorial. For now, all you need to know is that it maps URL roots to applications. In the end, you should have a file that looks like this:
    from django.conf.urls.defaults import patterns, include, url
    # Uncomment the next two lines to enable the admin:
    from django.contrib import admin
    urlpatterns = patterns('',
        # Examples:
        # url(r'^$', 'mysite.views.home', name='home'),
        # url(r'^mysite/', include('')),
        # Uncomment the admin/doc line below to enable admin documentation:
        # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
        # Uncomment the next line to enable the admin:
        url(r'^admin/', include(,

    (The bold lines are the ones that needed to be uncommented.)

Helpful django resources

%d bloggers like this: