Introduction to Django

Django is opensource Web framework written in Python. Django loosely follows MVC design pattern. Django being written in Python you should have some knowledge of Python. You can download Django from I have been using Django since its 0.96 release. Today I decided to write a small application using it.

As Django follows design pattern similar to MVC lets first understand what MVC is:

MVC Design Pattern

There are various MVC frameworks available like CakePHP, Zend Framework for PHP developers, Struts for Java developers, Catalyst for Perl developers and Rails for Ruby developers.


Model is generally used to interact with the databases. Suppose you are working on some social networking site and you want to get user’s friends list. All the queries regarding this is written in Models. The resultant output is passed on to Controller.


All the business logic goes here. Consider the same scenario where user wants to get his own friends list. At this time Controller will get some inputs from user. Inputs may be number of friends he wants to see at a time or may be the number of users from India. Based on the user inputs the Controller with interact with Model to get the friends list. And then the list is passed to View.


View are used for creating User Interface. In our case User Interface will be based on the friends list recieved from Controller. View will take care of how the list is going to be displayed and what details are to be displayed.

MVC pattern allows us the write the code which is easier to maintain, Programmer writes Model and Controller and at the same time Designer can create View. And also few changes somewhere wont affect the entire system. We can say that MVC applications are loosely coupled.

Django follows slightly modified version of MVC design pattern called MTV design pattern. MTV stands for Model-Template-View. Now lets see how Django’s MTV pattern is:

MTV Design Pattern


A Model in Django is a Python class which represents a table from database. You dont need to write complex SQL queries to get records from Database. You can do it by writing Python code itself.


In Django views contains all business logic code.


These are the HTML pages which create User Interface. Django comes with very powerfull templating system.

Get Set Code..

Now its time to create our application. The application will be a simple address book. We will make use of Django’s Admin to add records and will create a view to display the contacts in address book.

Lets create a new Django project. Run the following command:

$ startproject djangoapp

A new directory called list will be created which contains following files: So that Python treats this directory as package. Command line utility to interact with our project. Configuration file for our project. URL mappings of our project.

Django comes with light weight Web server. DONT USE IT FOR PRODUCTION. Next

$ cd djangoapp

And boot the webserver:

$ runserver

This will start Web server on port 8000(default). Visit http://localhost:8000/ from your browser. You should see “It worked!” message like this:


Now lets configure database connection for our application. Open the file. You will see the following lines:


For our application we are using MySQL and the database name is “addressBook”. So we have to edit above lines as follows:

DATABASE_NAME = 'addressbook'

Django’s models requires new application to be created. So type the following command to create new application:

$ python startapp addressbook

This will create new directory called friends with the following contents:

Change directory to friends:

$ cd addressbook

Edit and write following contents in it:

from django.db import models
class Contacts(models.Model):
    name = models.CharField(max_length=30)
    phone = models.CharField(max_length=30)
    email = models.EmailField()

The class Contacts will be a table in database and the variables ‘name’, ‘phone’ and ’email’ will be the columns of Contacts table. Yeah.. no need of writing SQL queries, Django can do it for you. We will see that later.

Now we need to tell Django to use this ‘Contacts’ model(djangoapp/addressbook/ Edit file, and goto INSTALLED_APPS section and add ‘addressbook’. It should look as follows:


Validating Models

$ python validate

The above command will validate models in your application. It will check for syntax and logical errors. If everything is ok then it should give 0 errors found message. And now run the following command to generate queries of the models:

$ python sqlall addressbook

In above command addressbook is the name of our app for which queries are to be generated. This wont create table in the database, it will just output the queries which will be executed at the time of creating tables. The table name will start with ‘addressbook_’ and ‘id’ column(Primary Key) is added by default. And now syncdb to create tables:

$ python syncdb

This will execute the statements which where generated by sqlall command. Now as we have our database ready, we will make use of Django’s Admin now. To use Admin we need to add ‘django.contrib.admin’ to INSTALLED_APPS:


And now again sync the database:

$ python syncdb

As we have added admin in INSTALLED_APPS, syncdb will now ask you to create superuser for the application. We need superuser to access admin. Now we have to add our model to admin. To do that create a file called in our application(i.e. Under djangoapp/addressbook/):

from django.contrib import admin
from djangoapp.addressbook.models import Contacts

And finally edit Add (r’^admin/(.*)’, in urlpatters so that we can access admin at http://localhost:8000/admin. Our file looks like this:

from django.conf.urls.defaults import *

# Uncomment the next two lines to enable the admin:
from django.contrib import admin

urlpatterns = patterns('',
    # Uncomment the next line to enable the admin:

Now run the server:

$ python runserver

You can access admin at http://localhost:8000/admin.


Click on Add link under Addressbook and start adding to the list. Django admin is very useful and it also provide every kinds of validations. Now we will write a view to display the added contacts. Open the file under addressbook and write the following:

from django.shortcuts import render_to_response
from models import Contacts

def contacts(request):
    contacts_list = Contacts.objects.all()
    return render_to_response('contacts_list.html', {'contacts_list': contacts_list})

In the above code we create a function called contacts. We retrieve all the records from Contacts model using Contacts.objects.all() . We use render_to_response to send variables to templates. The first argument is template name (contacts_list.html in our case) and second argument is a dictionary. The key in dictionary is the name of the variable that can be accessed in template contacts_list.html. The value in the dictionary is the variable that we will access in template. We have to create a directory called templates in addressbook and we will place contacts_list.html. In contacts_list.html we just loop through the contacts_list dictionary which we had passed in contacts function in

<head><title>Address Book</title><head>
<h1>Address Book</h1>
{% for contact in contacts_list %}
{{ }}</td>
{{ }}</td>
{{ }}</td>
{% endfor %}</table>

To see the output we have to map url to addressbook view. Change the so that it looks as follows:

from django.conf.urls.defaults import *
from addressbook.views import contacts
# Uncomment the next two lines to enable the admin:
from django.contrib import admin

urlpatterns = patterns('',
    (r'^show/', contacts),
    # Uncomment the next line to enable the admin:

You can see the list of contacts at http://localhost:8000/show/.

In this post we covered some basics about Django like admin, creating a view and using templates. I will be posting more about Django soon.



9 thoughts on “Introduction to Django

  1. Whilst I can see that Django is kind of cool because it seems to be able to do a lot of what Ruby on Rails can, but it just seems so… ugly and unwieldy in comparison. The commands are ugly, the syntax is not nearly as easy to read, and so on.

    Seems to me like this is a poor knock off of Rails, but for python.

  2. Great tuto.

    I think there is an error :

    in the last code exerpt (

    line 2 : from contacts.views import contacts
    should be changed to from addressbook.views import contacts

    Thanks for the tutorial.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s