Django Quick Start


This is a simple tutorial for getting a simple application running with Django. The Django Framework is a “a high-level Python Web framework that encourages rapid development and clean, pragmatic design”.

These are very simplified quick start instructions. Alternatively, for more detailed instructions you can follow the following official Django documents:

These instructions were tested on Mac OS X 10.4, results may vary for other platforms :)

Prerequisites

  • Python 2.3 or greater installed
  • Subversion
  • MySQL installed (not a prereq for Django, just what I will be using in this quick start)

Django Installation

sudo python setup.py install
  • Find the newly installed file django-admin.py and make sure that it is available in your PATH environment variable

Setup MySQL Python Database Adapter

sudo python ez_setup.py setuptools==dev
  • Run:
python setup.py build
  • Run:
sudo python setup.py install

Creating a Django Project

  • Create a directory for your Django project and cd to it
  • Run:
django-admin.py startproject djangotest

(djangotest is the name of our new project)

  • Change directory to the newly created project:
cd djangotest
  • Create a MySQL database to use for our project
mysql -u USERNAME -p
create database djangotest;
  • Edit settings.py
    • Set DATABASE_ENGINE = ‘mysql’
    • Set DATABASE_NAME = ‘djangotest’
    • Set DATABASE_USER and DATABASE_PASSWORD to your username and password for MySQL
  • Initialize database with initial tables
    • Run:
python manage.py syncdb
    • Answer the questions for default superuser, etc.

Now our “Project” should be setup. To do something interesting, we need to setup an “Application” within that project

Creating an Application

  • Run:
python manage.py startapp records

(records is our application name, a subdirectory “records” will be created)

  • In the new “records” directory, edit the file models.py. This is where we define the application models or entities that map to database tables. First lets make a simple set of models, Records which have an Artist:
from django.db import models

class Artist(models.Model):
	name = models.CharField(maxlength=128)

class Record(models.Model):
	artist = models.ForeignKey(Artist)
	title = models.CharField(maxlength=128)
	label = models.CharField(maxlength=64)
	release_date = models.DateTimeField('Date Released')

Now we need to “install” this new app so that we can access this new model. Edit settings.py in the root of our project and edit INSTALLED_APPS

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'djangotest.records',
)

We added ‘djangotest.records’ (djangotest is our project name, records is our application name).

Now, to set up our database schema to use the new model execute the following from the root of the project:

python manage.py sql records

Now sync up our new tables with the database:


python manage.py syncdb

We can now use the Django interactive shell by typing:

python manage.py shell

More on that later…

Generating the Automatic Admin App

Enable the admin app by editing settings.py again and adding ‘django.contrib.admin’ to the INSTALLED_APPS

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'djangotest.records',
    'django.contrib.admin',
)

Edit our models.py to enable the admin app for them. Add the inner class Admin to our classes. I’ve also spiced it up with some other stuff including a new Track class…

from django.db import models

class Artist(models.Model):
	name = models.CharField(maxlength=128)
	genre = models.CharField(maxlength=128)
	#The Admin inner class enables this class for the admin application
	class Admin:
		pass
		#columns that will appear on the list pages
		list_display = ('name', 'genre')
	
	#This is important for what will disply on record pages/edit controls for the artist	
	def __str__(self):
		return self.name
		

class Record(models.Model):
	artist = models.ForeignKey(Artist, edit_inline=models.STACKED)	
	title = models.CharField(maxlength=128, core=True)
	label = models.CharField(maxlength=64, core=True)
	release_date = models.DateField('Date Released')
	class Admin:
		pass
		list_display = ('title', 'artist', 'label', 'release_date')	
	def __str__(self):
		return self.title

class Track(models.Model):
	record = models.ForeignKey(Record, edit_inline=models.STACKED)
	title = models.CharField(maxlength=128, core=True)
	lengthInSeconds = models.IntegerField(core=True)
	class Admin:
		pass
		list_display = ('record', 'title')
	def __str__(self):
		return self.title

Re-run python manage.py syncdb

Edit urls.py and uncomment the line under # Uncomment this for admin: so that it looks like this:

from django.conf.urls.defaults import *

urlpatterns = patterns('',
    # Example:
    # (r'^djangotest/', include('djangotest.foo.urls')),

    # Uncomment this for admin:
     (r'^admin/', include('django.contrib.admin.urls')),
)

Now we can start the development server:

python manage.py runserver

Now you should be able to login to the application using the superuser account that you created earlier by going to: http://127.0.0.1:8000/admin/

Administration interface for our simple Records app