Welcome to Blogs @ Andrew Qu
Blog Index
All blogs
Search results

Learning Django


Django is a web framework using Python programming language. Using Django and an appropriate web server, you can build and host websites. In this post, I will record the steps as I learn.


To run django, you'll need to install Python, Django and an appropriate web server (for serious web hosting, for learning purposes, the builtin web server is enough).

If you are using Microsoft Visual Studio, I would recommend to use PTVS (Python tool for Visual Studio). Follow this link, Install PTVS for Visual Studio. You can also refer to my earlier post

If you are not using Visual Studio, follow this link: Install Django
To check Python and Django versions:
c:> python --version
  Python 2.7.2
c:> django-admin.py --version
Creating A New Website

All steps described here can be performed in Visual Studio with PTVS.

  1. Decide where to put the web site on your disk. I created a folder C:\Users\djwwwroot to host all web sites.
  2. > cd djwwwroot
  3. > django-admin.py startproject DjDemo
  4. The above will create the web site folder "DjDemo" with the initial files.
  5. In Visual Studio, the above can be done using File -> New -> Project -> Pytho -> Django Application
The web site has been created and can be viewed. To test,
> cd DjDemo
> python manage.py runserver localhost:8000
  Validating models...  0 errors found
  February 26, 2015 - 12:26:29
  Django version 1.5.3, using settings 'DjDemo.settings'
  Development server is running at http : //localhost:8000/
  Quit the server with CTRL-BREAK.
Now open a browser and enter the address localhost:8000/, you should see the following picture:

Using a Database

Django almost forces you to use a database. Most popular databases can be used. The simplest one is the built-in sqlite3. So open file settings.py and make the following changes:

        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'c:/Users/djwwwroot/DjDemo/model.db',  # Or path to database file if using sqlite3.
TIME_ZONE = 'Europe/London'
MEDIA_ROOT = 'c:/Users/djwwwroot/DjDemo/media'
Create folder "c:/Users/djwwwroot/DjDemo/media" which will be used to store file uploads.
To create the database, run
> python manage.py syncdb
  Would you like to create one now? (yes/no): yes
  Username (leave blank to use 'andrew.qu'): root
  Email address: your email
  Password: your passward

You'll notice a file named model.db is created in the project folder. You do not have to know how the database works. Django unifies the database interface regardless which database program you use. How data is managed will be discussed next.

Django Application

Upto now, we have created the project. Within the project, we cad add modules or the so called Django application. To create an application, run

> python manage.py startapp KeysApp
where KeysApp is the name of our first Django application. In the KeysApp, we are going to manage a set of key/value pairs.

By examining folder KeysApp, we find the following files,

models.py views.py tests.py
Django follows MVC (Model-View-Controller) philosophy. models.py will define the application model. views.py defines the application views. Django also automatically adds unit tests in tests.py

Now let's create our first model by modifying models.py file:

# Create your models here.
class KeyValue(models.Model) :
   key_name = models.CharField(max_length=60)
   key_value  =models.CharField(max_length=4096)
   created = models.DateTimeField('date created', auto_now=True)
We have created the KeysApp, but its not yet known to the DjDemo project. For a project to know about an application, we need to add it to the settings.py file as an INSTALLED_APP. So edit settings.py:
    # 'django.contrib.admindocs',
Therefore, Django applications can be used in multiple projects. Now it's time to run syncdb again. Every time you change the model, you'll need to syncdb. The command is
python manage.py syncdb
With the database table created, we can play with the table using Django:
> python manage.py shell
>>> from KeysApp.models import KeyValue
>>> kv = KeyValue(key_name='name', key_value='John')
>>> kv.save()
>>> kv = KeyValue(key_name="address", key_value="John's address")
>>> kv.save()
>>> kv.id
>>> kv.key_name
>>> kv.key_value
"John's address"
>>> kv.created
datetime.datetime(2015, 2, 26, 14, 47, 44, 444000, tzinfo=)
>>> KeyValue.objects.all().filter(id=2).delete()
>>> KeyValue.objects.all()
[<KeyValue: name-John>]
The Admin Page

Django automatically adds a site admin page. But it is not turned on by default. To turn it on, edit settings.py:

    # Uncomment the next line to enable the admin:
    # Uncomment the next line to enable admin documentation:
Edit urls.py:
# Uncomment the next two lines to enable the admin:
from django.contrib import admin

urlpatterns = patterns('',
    url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
    url(r'^admin/', include(admin.site.urls)),
Restart your server:
python manage.py runserver localhost:8000
Browse page address: http: //localhost:8000/admin/ and login with the root account created earlier. You should see the admin page in the browser.

To register the KeyValue model with the admin page, add file KeysApp/admin.py

from django.contrib import admin
from KeysApp.models import KeyValue
Restart the server and refresh the web page, you should see the "Key values" model on the admin page. Click on it, the next page should display the tables in the model.

Index Page to KeysApp

We'll now add a new page that initially simply displays a welcome message. In Django, a page is a view function. So to dadd a page, we need to add a view first. Edit KeysApp/views.py and add:

from django.http import HttpResponse

def index(request) :
   return HttpResponse("Welcome to KeysApp home page " + request.path + " !")
This will simply display a welcome message when it is rendered in a browser. Now we must link the web page address to the view function so the address sent to the web server will be routed to our index() function. This is done through url patterns. Add a new file KeysApp/url.py with the following:
from django.conf.urls import patterns, url
from KeysApp import views

urlpatterns = patterns('',
    url(r'^$', views.index, name='index'),
which simply matches the empty string to the index() function. However, when the framework matches addresses, it only looks in the project level urls.py file. Therefore, we need to include this file in the project leve urls.py file. To do this, edit DjDemo/urls.py file as follows:
urlpatterns = patterns('',
    # Examples:
    url(r'^admin/', include(admin.site.urls)),
    url(r'^keys/', include('KeysApp.urls')),
That means, all matching addresses that starts with "keys/" should be further matched in KeysApp.urls.

Now browse to http: //localhost:8000/keys/, the page should display the Welcome message.

Html Formatting Using Templates

Django uses template files for webpage formatting. Within the template files, you can embed some Python code. To do this, let's first add a template file in KeysApp/Templates/kv_page.html, with the following contents:

<head><title>Key and values</title></head>
<table style="margin-left:auto; margin-right:auto;" >
{% if all_pairs %}
    <tr style="text-align:left;"><th style="min-width:50px;">Name</th><th>Value</th>
    {% for kv in all_pairs %}
        <tr><td>{{ kv.key_name }}</td><td>{{ kv.key_value }}</td></tr>
    {% endfor %}
{% else %}
    <tr><td>No items to list yet.</td><td></td></tr>
{% endif %}
    <tr><td colspan='2'><hr /></td></tr>
    <tr><td colspan='2'>
    <form method="post" enctype="multipart/form-data" action="{% url 'create' %}" >
      {% csrf_token %}
      Key name : <input type="text" name="kn" style="width:200px;"/><br /><br />
      Key value : <input type="text" name="kv" style="width:200px;" /><br /><br />
      <input type="submit" name="send" value="Create New Key" />

This is basically an html file with some specfic python code.
{% ... %} -- Tags or control statements (for, if, block, extends)
{{ ... }} -- Variables
{{ var|filter }} -- Filters, for example, {{ name|lower }}
See more details at Django template language

Add to views.py:

def create_key(request) :
   kvs = KeyValue.objects.filter(key_name=request.POST['kn'])
   if len(kvs) > 0 :
      return HttpResponse("Key " + request.POST['kn'] + " already exists. Please choose a different key")
   else :
      kv = KeyValue(key_name=request.POST['kn'], key_value=request.POST['kv'])
      return HttpResponseRedirect(reverse('index'))

Add to KeysApp/urls.py :

    url(r'^create/$', views.create_key, name='create'),

Now browse to "http: //localhost:8000/keys/", and play with the page:

Download final source code.
Ads from Google
Dr Li Anchor Profi
Engineering anchorage plate design system
©Andrew Qu, 2014. All rights reserved. Code snippets may be used "AS IS" without any kind of warranty. DIY tips may be followed at your own risk.