April 15th, 2012

Django Tutorial: Introduction

Tutorial for: Django

Requirements:

This is the first part of a Django tutorial which will go through building a simple wiki. This introduction will explain how to install Django and start a project.

I thought of creating this tutorial after I went through the Pyramid tutorial, which explains how to build a simple wiki in roughly 20 minutes, perhaps more. Django's main tutorial doesn't really have a good example application, one which makes use of Django's great abilities. I understand a tutorial is suppose to be very simple, but the Django tutorial goes a little overboard in this regard and leaves out some crucial components that new developers to Django should know about.

Firstly, take a look at the Python packages in the dependency list, I will explain them briefly here to explain what we will be using them for in this tutorial project:

South
This is used for database migrations, everyone using Django should be using this.
django_debug_toolbar
This is the same debug_toolbar which you can see in the Pyramid project, but this one is for Django. It is good to have during development.

We will use additional packages in later tutorials in this set. Once additional tutorials in this set are ready, you will see a Next tutorial link at the bottom of this tutorial. Also, please feel free to comment on this tutorial.

If you are a Windows user, please download the Instant Django download for Windows. If you are using a *NIX operating system, such as OS X or Linux, use your standard Python tools to install Django with PIP:

# pip install django

The first thing we need to do, is create a new project, this is done using the django-admin command. It is added to your PATH on most operating systems, if you downloaded the Instant Django for windows, it is in your path as well.

$ django-admin startproject djwiki

This will create a very simple project layout. It will contain the following files manage.py, settings.py, and urls.py. Lets go through each one briefly to explain what each one contains:

manage.py
This is used to manage your project. It is used to sync the database, add new apps, or perform various configurations based on which installed apps you have.
settings.py
Your projects configuration. This tells your project which resources to load, and where external resources can be found, such as templates.
urls.py
Contains the URL mappings for your project root. You can place the url mappings for your apps here as well, but it is not recommended.

Now that the formalities are out of the way, lets get to editing the settings.py module to tell Django a little bit about our project. Here are some values we are going to be focusing on during this tutorial:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': '/home/kveroneau/workspace/djwiki/sqlite.db',                      # Or path to database file if using sqlite3.
        'USER': '',                      # Not used with sqlite3.
        'PASSWORD': '',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}
MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)
TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Uncomment the next line to enable the admin:
    # 'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
)

Above, you will notice that I went ahead and configured the DATABASE settings. This has been auto-generated using Eclipse. Read Getting Started using Python in Eclipse to learn how to get Eclipse up and running on your machine. Modify the MIDDLEWARE_CLASSES, TEMPLATE_DIRS, and INSTALLED_APPS to be the following:

INTERNAL_IPS = ('127.0.0.1',)
MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'debug_toolbar.middleware.DebugToolbarMiddleware',
)
TEMPLATE_DIRS = (
                 '/home/kveroneau/workspace/djwiki/templates',
)
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.admin',
    'south',
    'debug_toolbar',
    'wiki',
)

Here we're telling Django where to find our templates, in a production project, you should use os.path to make the setting dynamic. You can place the newly created variable INTERNAL_IPS anywhere in the file, it is there for the debug_toolbar. In the apps section, we enabled the admin app, and added the wiki, which we will create right away:

$ python manage.py startapp wiki

This will create a new directory called wiki with the following files: models.py, tests.py, and views.py. I will go through each briefly:

models.py
This module defines your data models which are connected to a database.
tests.py
This contains your application test files, this is used to test the application programmatically.
views.py
Arguably the most valuable module in an app, it contains all the logic used to render a view.

There are a few other modules you may wish to add, urls.py, and forms.py. The first one is highly recommended, as it enables your app to be portable between multiple Django sites. The second one is to store forms, which are either connected to data models, or independent. Lets start by creating a simple urls.py to confirm everything is working correctly:

from django.conf.urls.defaults import patterns, url

urlpatterns = patterns('wiki.views',
    url(r'^$', 'index'),
)

This will define a very simple view will create right away. urlpatterns needs to contain a special object built by patterns. The first parameter there is the base module where the views will be fed from. If we did not place wiki.views as the first parameter and instead an empty string, then the url function will need to be built like this:

url(r'^$', 'wiki.views.index'),

Django contains lots of shortcuts to make developing an application incredibly easy and less frustrating. Here is a simple index view that returns Hello World:

from django.http import HttpResponse

def index(req):
    return HttpResponse('<html><body>Hello World!</body></html>')

In this tutorial, we will start with function-based views and will evolve to class-based when we build the actual wiki. This example is very simple, it just returns an HttpResponse with the text Hello World. Here is the glue for the project's url.py to enable this view to function:

from django.conf.urls.defaults import patterns, include, url

from django.contrib import admin
admin.autodiscover()

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

To test out the configuration, start the development server by entering in the following:

$ python manage.py syncdb
$ python manage.py runserver

To view the example, visit http://localhost:8000/wiki/ in your browser. You should see the text Hello World appear on the screen. This confirms that the URL mapping and everything is working correctly in your installation. When you run syncdb for the first time, it will prompt you for a superuser account. This is part of the flow from the auth app. Once you visit the site in your web browser, you should notice the debug toolbar on the right side. It contains a good amount of helpful information. Now lets create the data model for our wiki:

from django.db import models

class Page(models.Model):
    name = models.CharField(max_length=40, unique=True)
    content = models.TextField()

This data model is extremely simple, as I am taking the exact model used in the Pyramid tutorial. Later in this tutorial, we will expand on it to add extra fields which are useful to simple wikis. Once the model is written and saved, we need to add a new migration in South for it. Here is how we begin a migration:

$ python manage.py schemamigration wiki --initial
$ python manage.py migrate wiki

I encourage you to read through the South documentation on how this all works, basically the first command creates an initial migration of what the data model currently looks like, and migrate applies the change to the database. In this case, it creates a new table.

To end the first part of this tutorial set, we will enable the wiki to be edited in the Admin interface, and this step is very easy. I will not go into detail on how to customize the admin interface, just yet. First, you will need to create a new file in the app's directory called admin.py, and place the following code into it:

from django.contrib import admin
from djwiki.wiki.models import Page

admin.site.register(Page)

Now, terminate the development server and re-run it. Your assignment until the next tutorial in this set, is to add pages to your Wiki using the admin interface. Make the Name field a WikiWord, so that it will be compatible with the code in the next tutorial in this set.

May 4, 2012, 4:59 a.m. - Harsh

Nice tut. Waiting for the next parts.

Dec. 2, 2012, 3:35 p.m. - Daniel

Hi Kevin! Will you write the next tutorial soon? Looking forward to it.

Feb. 26, 2013, 6:25 a.m. - C.

Hey Kevin, keep up the nice work! (Eagerly waiting for the second part of the tutorial). Greetings, C.

About Me

My Photo
Names Kevin, hugely into UNIX technologies, not just Linux. I've dabbled with the demons, played with the Sun, and now with the Penguins.




Kevin Veroneau Consulting Services
Do you require the services of a Django contractor? Do you need both a website and hosting services? Perhaps I can help.

If you like what you read, please consider donating to help with hosting costs, and to fund future books to review.

Python Powered | © 2012-2014 Kevin Veroneau