Practical Django Projects

Author: James Bennett
Publisher : Apress
ISBN : 1590599969
Pages : 256


This book was written by James Bennett who is the release manager for the open source Django project.

Developing web sites is a
complex work, and much of that work ends up being repeated for each new application.

This has lead to the development of web frameworks.

Django is one of the most recent web frameworks. It achieves rapid application development and flexible, reusable code.

Chapter 1: Introduction to Django

Django is an open source project written in Python. There is a separate article about Django.

Chapter 2: Your First Django Site: A Simple CMS

Configuring Your First Django Project

First run startproject cms.
THen edit

DATABASE_NAME = 'cms.db'

After providing basic configuration data to Django, you can synchronize the database with the command:

python syncdb

Putting Together the CMS

You have to add two applications:

  • django.contrib.flatpage : Provides a data model for a simple page.
  • django.contrib.admin: Powerful administrative interface that can work with any Django data model.

Edit and add the following lines:


The you must run syncdb again: python syncdb

Next, open and uncomment the following line:

# Include these import statements...
from django.contrib import admin
# And include this URLpattern...
urlpatterns = patterns('',
    # ...
    (r'^admin/', include(,
    # ...

The you must run syncdb again: python syncdb

To launch the built-in web server run: python runserver
and visit

To create a flat page: * login to admin and click Add next to Flat Pages.

  • In the URL field enter /first-page/
  • In the Title field, enter My first page.
  • In the Content field, enter This is my first Django flat page.
  • click Save

To add this page to the urls open up and add the following line below the one for the admin interface:


This means that it will match any url.

Django Template System

By default, django.contrib.flatpages looks for a template file named flatpages/default.html.

We have to define a template directory in Add the following:


Now create file /home/chrys/django-templates/cms/flatpages/default.html and add the following:

        <title>{{ flatpage.title }}</title>
        <h1>{{ flatpage.title }}</h1>
        {{ flatpage.content }}
Save the file and browse page {{}}.

Chapter 3: Customizing the Simple CMS

Adding Rich-Text Editing

To add TinyMCE you have to do the following:

  • Download tinymce
  • Unpack it somewhere and make a note of the path with the jsripts/tiny_mce/ directory.
  • Add the following to
from django.conf.urls.defaults import *
urlpatterns = patterns('',
    # Example:
    # (r'^foo/', include('')),
    # Uncomment this for admin:
    (r'^admin/', include('django.contrib.admin.urls')),
    (r'^tiny_mce/(?P<path>.*)$', 'django.views.static.serve',
                            { 'document_root': '/path/to/tiny_mce' },

Replace the /path/to/tiny_mce part with the actual location on your computer of the
tiny_mce directory. Make sure you add this line below the admin line.

Adding a Search System to the CMS

You need to create a new application for this. So type: python startapp search

Open file search/ and type the following:

from django.http import HttpResponse
from django.template import loader, Context
from django.contrib.flatpages.models import FlatPage
def search(request):
query = request.GET['q']
results = FlatPage.objects.filter(content__icontains=query)
template = loader.get_template('search/search.html')
context = Context({ 'query': query, 'results': results })
response = template.render(context)
return HttpResponse(response)

Next you need add the following to {search/search.html}}.

 <p>You searched for "{{ query }}"; the results are listed below.</p>
{% for page in results %}
<li><a href="{{ page.get_absolute_url }}">{{ page.title }}</a></li>
{% endfor %}

The above template makes use of the variables that are passed from, query and results.

Next, open file flatpages/default.html and place the following:

<form method="get" action="/search/">
<p><label for="id_q">Search:</label>
<input type="text" name="q" id="id_q" />
<input type="submit" value="Submit" /></p>

Finally, open the project's and add the following:

r'^search/$', ''),

Chapter 4: A Django-Powered Weblog

Feature Checklist

  • Easy way to add entries
  • Support of multiple authors
  • Each entry should allow an optional excerpt
  • The authors should be able to create categories and assign entries to them.
  • Authors should be able to decide which entries will be displayed publicly and which will not.
  • Entries should be able to be featured.
  • A link log should be provided.
  • Both entries and links should support tagging.
  • The link log should integrate with
  • Visitors should be able to browse entries and links by date, by tag or by categories.

Creating the Weblog Application

This is going to be a standalone application. First you need to add it to PYTHONPATH. Type the following:
export PYTHONPATH=/home/user/python-code:$PYTHONPATH

or add this line to your profile.

In the same directory you created the cms project, create a new directory name coltrane. Inside create three files, and

Designing the Models

Open file and type:

class Category(models.Model):
  title = models.CharField(max_length=250, help_text='Maximum 250 characters')
  slug = models.SlugField(prepopulate_from=['title'], unique=True, help_text="Suggested value automatically generated from title. Must be unique")
  description = models.TextField()
  def __unicode__(self):
return self.title
  def get_absolute_url(self):
     return "/categories/%s/" % self.slug
 class Meta:
   ordering = ['title']
   verbose_name_plural = "Categories"

More information about [* SlugField]

Open cms/ and add the coltrane application:


Create coltrane/ and add the following:

from coltrane.models import *

Then run python syncdb.

The Entry Model

Open and below the Category model, add the Entry model.

import datetime
class Entry(models.Model):
  title = models.CharField(max_length=250)
  excerpt = models.TextField(blank = True)
  body = models.TextField()
  pub_date = models.DateTimeField(
  slug = models.SlugField(prepolate_from=['title'], unique_for_date='pub_date')
++ Authors, Comments and Featured Entries
[[code type="Python"]]
from django.contrib.auth.models import users
author = models.ForeignKey(User)
Another feature is to allow/disallow comments. So add a field for it:
[[code type="Python"]]
enable_comments = models.BooleanField(default=True)
++ Different Types of Entries
Specify a list of choices and allow the user to select from them. If there is a need for more choices, they can simply be added to the list.
[[code type="Python"]]
  (1, 'Live'), 
  (2, 'Draft'),
status = models.IntegerField(choices=STATUS_CHOICES, default=1)

Chapter 5

Chapter 6

Chapter 7

Chapter 8

Chapter 9

Chapter 10

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.