Practical Django Projects

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

Introduction

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 django.admin.py startproject cms.
THen edit settings.py.

DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = 'cms.db'

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

python manage.py 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 settings.py and add the following lines:

INSTALL_APPS = (
 'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'django.contrib.flatpages',
)

The you must run syncdb again: python manage.py syncdb

Next, open urls.py and uncomment the following line:

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

The you must run syncdb again: python manage.py syncdb

To launch the built-in web server run: python manage.py runserver
and visit http://127.0.0.1:8000/admin/.

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 urls.py and add the following line below the one for the admin interface:

(r'',include('django.contrib.flatpages.urls')),

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 settings.py. Add the following:

TEMPLATE_DIRS = (
    '/home/chrys/django/django-templates/cms/',
)

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

<html>
    <head>
        <title>{{ flatpage.title }}</title>
    </head>
    <body>
        <h1>{{ flatpage.title }}</h1>
        {{ flatpage.content }}
    </body>
</html>
 
Save the file and browse page {{http://127.0.0.1:8000/first-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 urls.py
from django.conf.urls.defaults import *
urlpatterns = patterns('',
    # Example:
    # (r'^foo/', include('foo.foo.urls')),
    # 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 manage.py startapp search

Open file search/views.py 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}}.

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

The above template makes use of the variables that are passed from views.py, 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>
</form>

Finally, open the project's urls.py and add the following:

r'^search/$', 'cms.search.views.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 del.icio.us
  • 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 init.py, models.py and views.py.

Designing the Models

Open file models.py 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 [* http://programmingexamples.wikidot.com/django-model-layer#toc17 SlugField]

Open cms/settings.py and add the coltrane application:

INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'django.contrib.flatpages',
'cms.search',
'coltrane',
)

Create coltrane/admin.py and add the following:

from coltrane.models import *
 
admin.site.register(Category)

Then run python manage.py syncdb.

The Entry Model

Open models.py 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(default=datetime.datetime.now)
  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)
[[/code]]
 
Another feature is to allow/disallow comments. So add a field for it:
[[code type="Python"]]
enable_comments = models.BooleanField(default=True)
[[/code]]
 
++ 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"]]
STATUS_CHOICES = (
  (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.