Home Accessibility Courses Diary The Mouth Facebook Resources Site Map About Us Contact
A framework with python - Django - first steps

What is Django and what do I need to be able to use it?

Django is a framework - a tool that lets you create, customise, run and maintain web sites in which the data is stored in database tables. It uses the DRY (Don't Repeat Yourself) philospohy of design - quite the opposite of early web sites, where we saw large amounts of repeated information in page after page, and updating the web site (especially where it was the look and feel or common page furniture that needed changing) was a something of a boring and repetitive task - which was ineffcient and easily lead to inconsistencies. Django is called a framework as it looks after the frame (Citation needed, as they say on Wikipedia ;-) ) and leaves you to concentrate on the content of your site. It's written in Python, and you define your data / look after your application's functionallity using Python too.

If you've come across Rails, it's roughly the equivalent for Ruby. Mason works along similar lines for Perl, and CakePHP, Zend, CodeIgniter, Yii and Symfony are among a long list of PHP frameworks.

All frameworks (and Django is no exception) have quite a number of component elements to set up ahead of time. This is the downside of DRY - you need to have the structure to manage and maintain your information, and to apply the common look and feel to all your pages, from the single source in which it is held. So there's quite a bit to setting it up. Actually, Django is easier than most, though you may not think so if it's your first ever framework.

Prerequisite: python - a version 2.5 to 2.7 Python

Yep - that's it! These versions of Python come with the Sqlite database, which will serve excellently for your test database (and in smaller production environments too). And Django comes with its own test web server, so you can try out your web application without even setting up a server.

In time, you probably will want to run Django under Apache httpd or a similar server rather that through the test server providesd, and it's quite likely that you'll want to use a database server archirecture such as MySQL, Oracle or PostGreSQL rather that SQLite, and it's straightforward to do so.

You can't run Django on Python 3.x (yet!?); conversion from Python 2 to Python 3 isn't trivial for things like Django (nor for numpy, scipy, ..). You can use Python 2.4, but SQLite isn't built in, so you'll need to have one of the other databases running.

How do I download and install Django?

Download from http://www.djangoproject.com/download/. I suggest the latest production version - 1.2.4 at the time of thesse notes being written, but should be 1.3 soon. You're not going to be pushing the bounds of the technology as you get to know Django, so don't go for one of the leading edge / bleeding edge releases.

Create a directory within your home, move the downloaded file there, and unpack it. For these notes, my computer is called "munchkin", my user name is grahamellis and my home directory is /Users/grahamellis. The computer is running Mac OS X 10.6.4 (Snow Leopard) ... and that's about all you need to know to read the notes.

munchkin:django grahamellis$ pwd
/Users/grahamellis/django
munchkin:django grahamellis$ tar xzvf Django-1.2.4.tar.gz
munchkin:django grahamellis$ cd Django-1.2.4
munchkin:django grahamellis$ sudo python setup.py install


The setup.py script copies all of the stuff from the distribution to Python's library directories; they're in the system are and so you'll need admin priviledges. When you've entered your password on that last command, you'll see screenfulls of details of files being copied ...

Once that's done, check that it worked - that you can see the django package from python, and that the admin script is avaialble and on your path.

munchkin:Django-1.2.4 grahamellis$ python
Python 2.6.1 (r261:67515, Dec 17 2009, 00:59:15)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> print django.get_version()
1.2.4


munchkin:django grahamellis$ which django-admin.py
/usr/local/bin/django-admin.py
munchkin:django grahamellis$


What are the elements of Django and an django application?

When you ran that setup script up above, you loaded / unpacked amongst others ...

a) A command line utility program called django-admin.py which (as the name suggests) lets you do various admin tasks for django from the command line

b) A standard admin application which will run within you Django based site and let you do various admin tasks to the data that the application looks after (you don't actually have to use this is you write all your own data admin)

c) A whole load of code which you'll be using within your Django based site's pages to provide the glue and functionallity

d) Templates for what a fresh project and fresh application look like (terms will be defined in a minute), and also templates for what the pages in standard applications like the admin app will look like.

e) The test server

Note - you've unpacked these things. You've not configured, started or run them so far.

Now ... looking at the elements we're going to build and run to give us a working website. Some terms.

A project is a directory / folder into which we'll place / build our site (or one element on its tree). Within a project, we'll have one or more apps - individual applications, and these applications may be invoked later on through multiple projects. Within an application, we'll have one or more classes which mirror database tables to hold our data.

In order to keep the first examples in these notes short, I'm going to write ONE project (called "oursystems") in which I will build ONE application (called "net"). The application is going to be based around ONE table (called "System") and I am going to allow myself three columns of data in that table - they'll be the system's name, the system's IP address, and a piece of text about the system.

The data (and its immediate handlers) are known as the model. The way the data is displayed on the screen - the surrounding framework and where bits of data are popped into it - is known as the view. And the elements which transform the data in the model to what appears on the screen are known as the controller.

Creating a new project

Let's create our project, using the command line admin script (make sure you're in the django directory!):

munchkin:django grahamellis$ django-admin.py startproject oursystems
munchkin:django grahamellis$ ls oursystems/
__init__.py manage.py settings.py urls.py
munchkin:django grahamellis$


__init__.py indicates this is a package to Python
manage.py is a command line script to manage the individual project (as compared to django-admin which looks after the whole django installation)
settings.py is a configuration file you'll be editing very soon to set up the model
urls.py is a configuration file you'll be editing later to map web addresses (URLs) to project, application, page

Change into the project directory, and use the manager to start the test server:

munchkin:oursystems grahamellis$ python manage.py runserver
Validating models...
0 errors found
 
Django version 1.2.4, using settings 'oursystems.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.


This is really just to re-assure you that the server is there, running, and that it's picked up the empty settings which are complete - it's really your first checkpoint since you started that you've not made any catastrophic errors.

Browse to 127.0.0.1:8000 to see the result:

First Install - Django

If you prefer to view your web pages via a network, you can start the server giving an IP address and a TCP port number - add something like 192.168.200.198:8765 onto the end of the runserver command. The IP address must be (the) one that's serviced by your computer, and the port number you choose should not be in use for anything else. That's a story for me to tell on a networking post, not during a Django one!

When you've seen that work, you can kill the test web server - ^C as it says.

Your project will want to connect to a database - there is no default, so you should edit the Python source in settings.py. For SQLite, only the Engine and Name need be changed - the Engine setting being specific to the database that we're using and the Name being a complete, absolute path to the file in which the SQLite database will be held. For MySQL, etc, there will be rather more settings like user names and passwords ... and perhaps IP addresses and ports too.


'ENGINE': 'django.db.backends.sqlite3',
'NAME': '/Users/grahamellis/django/oursystems/data.sql3',


Back to that manage script we used before. We have now defined a database connection, but the database file doesn't exist - let alone the default initial takes that Django needs within it. Run the manage script with a syncdb subcommand, and it will create all the files and tables that don't (yet) exist, but leave stuff that's already ben done (none so far) in place. We'll keep coming back to syncdb later on.

munchkin:oursystems grahamellis$ python manage.py syncdb
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_user_permissions
Creating table auth_user_groups
Creating table auth_user
Creating table auth_message
Creating table django_content_type
Creating table django_session
Creating table django_site
 
You just installed Django's auth system, which means you don't have any superusers defined.
Would you like to create one now? (yes/no): yes
Username (Leave blank to use 'grahamellis'):
E-mail address: graham@wellho.net
Password:
Password (again):
Superuser created successfully.
Installing index for auth.Permission model
Installing index for auth.Group_permissions model
Installing index for auth.User_user_permissions model
Installing index for auth.User_groups model
Installing index for auth.Message model
No fixtures found.
munchkin:oursystems grahamellis$


If you do a directory listing, you'll see that the database file has been created and you'll also see that there are now .pyc files which indicate that python's read and used the settings and url files.

munchkin:oursystems grahamellis$ ls
__init__.py data.sql3 settings.py settings.pyc urls.pyc
__init__.pyc manage.py settings.py.orig urls.py
munchkin:oursystems grahamellis$


You can also check the sqlite tables directly if you've got a command line sqlite utility on your machine (it's not part of the Python or Django libraries - don't worry if you've not got it on your computer).

munchkin:oursystems grahamellis$ sqlite3 data.sql3
SQLite version 3.6.12
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .tables
auth_group auth_user_groups
auth_group_permissions auth_user_user_permissions
auth_message django_content_type
auth_permission django_session
auth_user django_site
sqlite> .quit
munchkin:oursystems grahamellis$


Or in more detail

munchkin:oursystems grahamellis$ sqlite3 data.sql3
SQLite version 3.6.12
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .schema
CREATE TABLE "auth_group" (
"id" integer NOT NULL PRIMARY KEY,
"name" varchar(80) NOT NULL UNIQUE
);
etc
sqlite> .quit
munchkin:oursystems grahamellis$


Creating an application within the project

Back to manage.py to create the application (called nets); you can then look at your directory structure to see what it's achieved:

munchkin:oursystems grahamellis$ python manage.py startapp nets
munchkin:oursystems grahamellis$ ls
__init__.py data.sql3 nets settings.py.orig urls.py
__init__.pyc manage.py settings.py settings.pyc urls.pyc
munchkin:oursystems grahamellis$ ls nets
__init__.py models.py tests.py views.py
munchkin:oursystems grahamellis$


We'll come to views.py and test.py later. Initially (and this is where the coding really starts!) we need to define our database table(s) in models.py. To keep this first Django app truely a "Hello World" one - minimalist - we've just used a single class / table and a single column type in our database - though we have allowed ourselves the luxury of three columns.

The following is written into models.py:

from django.db import models
class System(models.Model):
  name = models.CharField(max_length=32)
  ip = models.CharField(max_length=15)
  about = models.CharField(max_length=200)


We also need to include the nets application within the oursystem project settings file so that the project server knows that the nets application should be served. Edit settings.py (add in 'nets', - other lines shown for context):

INSTALLED_APPS = (
  'django.contrib.auth',
  'django.contrib.contenttypes',
  'django.contrib.sessions',
  'django.contrib.sites',
  'django.contrib.messages',
  'nets',


The sql option on the manage.py script will let us check our edits - it'll tell us how the tables would be created - but it won't actually do the job. Let's see:

munchkin:oursystems grahamellis$ python manage.py sql nets
BEGIN;
CREATE TABLE "nets_system" (
"id" integer NOT NULL PRIMARY KEY,
"name" varchar(32) NOT NULL,
"ip" varchar(15) NOT NULL,
"about" varchar(200) NOT NULL
)
;
COMMIT;
munchkin:oursystems grahamellis$


Looks good ... let's have syncdb do it!

munchkin:oursystems grahamellis$ python manage.py syncdb
Creating table nets_system
No fixtures found.
munchkin:oursystems grahamellis$


Adding some data within the application

Let's add some data - for a first test and check - using the Python interactive console. manage.py can set up most of the environment for you so that all you've got to do is import the model class.

munchkin:oursystems grahamellis$ python manage.py shell
Python 2.6.1 (r261:67515, Dec 17 2009, 00:59:15)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from nets.models import System
>>> System.objects.all()
[]


That confirms that the table has started empty. Lets add some data (and - note - you MUST commit it to the database with the save method.

>>> item = System(name="Wizard",ip="192.168.200.199",about="Graham - 17 inch Mac laptop intel")
>>> item.save()
>>> System.objects.all()
[<System: System object>]
>>> item = System(name="Munchkin",ip="192.168.200.198",about="Graham - 11 inch MacBook Air")
>>> item.save()
>>> System.objects.all()
[<System: System object>, <System: System object>]
>>>


It's worked ... but there's no __str__ or __unicode__ method defined for your System class, so you just saw a defaut object printout. Add a __unicode__ method to the System object:

munchkin:oursystems grahamellis$ vi nets/models.py
munchkin:oursystems grahamellis$ cat nets/models.py
from django.db import models
 
class System(models.Model):
  name = models.CharField(max_length=32)
  ip = models.CharField(max_length=15)
  about = models.CharField(max_length=200)
  def __unicode__(self):
    return self.name + " at " + self.ip


And look again at the System Objects

Python 2.6.1 (r261:67515, Dec 17 2009, 00:59:15)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from nets.models import System
>>> System.objects.all()
[<System: Wizard at 192.168.200.199>, <System: Munchkin at 192.168.200.198>]
>>>

Using the Admin application to view and update the model

Rather that set up our own view and controller, we'll start with one that's already written - the admin application, which we'll set up. Firstly, we need to set up the URL mapping in url.py; uncomment the following lines;

from django.contrib import admin
admin.autodiscover()
(r'^admin/', include(admin.site.urls)),


In settings.py, uncomment the line that loads the admin application:

'django.contrib.admin',

Create the new database table that's needed:

Creating table django_admin_log
Installing index for admin.LogEntry model
No fixtures found.
munchkin:oursystems grahamellis$

Add "admin" to the end of the server URL ... and restart the server

Vanilla Django Admin


Admin - django


Create a file that allows the admin interface to see the System table in the nets app (admin.py)

munchkin:nets grahamellis$ cat admin.py
from nets.models import System
from django.contrib import admin
admin.site.register(System)


And you'll need to stop and start the django server

[17/Jan/2011 11:56:17] "GET /admin/ HTTP/1.1" 200 1882
[17/Jan/2011 11:57:58] "POST /admin/ HTTP/1.1" 302 0
[17/Jan/2011 11:57:58] "GET /admin/ HTTP/1.1" 200 3368
^Cmunchkin:oursystems grahamellis$ python manage.py runserver
Validating models...
0 errors found
etc


Changing data via Django admin


Customising the view

Let's start with customising the look and feel of the admin application that's already running; firstly, tell Django where to look for the templates, via settings.py:

TEMPLATE_DIRS = (
# Don't forget to use absolute paths, not relative paths.
'/Users/grahamellis/django/oursystems/templates'
)


and copy the standard template for the admin base there.

munchkin:oursystems grahamellis$ mkdir -p /Users/grahamellis/django/oursystems/templates/admin
munchkin:oursystems grahamellis$ cp ~/django/Django-1.2.4/django/contrib/admin/templates/admin/base_site.html /Users/grahamellis/django/oursystems/templates/admin


And edit it

munchkin:admin grahamellis$ vi base_site.html

For the moment ... just change some of the basic text, and rerun the admin application to see the effect.

Tailored Django admin


The admin app - Django


What next?

We're about halfway through this introduction to Django. We've installed it, set up a project and the model for an simple application within it. We've turned on the admin app to look at (and update) the data via its views.

Next steps ... to define our own data views, and controllers to define how the data from the model is viewed. And to add further tables and data column types, joined as appropriate, to the model.

UPDATE - next steps added (article no. 2 in this series - views and starting with templates - is [here].

Here's the file layout in the project directory:

Django directory structureSample files (these are the ones that have been entered during this session, or modifed, as they were by the end of the session):
admin.py
base_site.html
models.py
settings.py
urls.py


(written 2011-01-17, updated 2011-01-19)

 
Associated topics are indexed as below, or enter http://melksh.am/nnnn for individual articles
Y113 - Python and SQL databases
  [4086] Cacheing class for Python - using a local SQLite database as a key/value store - (2013-05-14)
  [4024] SQL databases from Python - an SQLite example - (2013-03-02)
  [3139] Steering our Python courses towards wxPython, SQLite and Django - (2011-01-19)
  [2790] Joining a MySQL table from within a Python program - (2010-06-02)
  [2786] Factory methods and SqLite in use in a Python teaching example - (2010-05-29)
  [2746] Model - View - Controller demo, Sqlite - Python 3 - Qt4 - (2010-04-29)
  [2745] Connecting Python to sqlite and MySQL databases - (2010-04-28)

Y306 - Python - The Django web framework
  [4095] Django - first steps - Updated - (2013-05-19)
  [4013] Web Frameworks - nested templates - (2013-02-22)
  [3919] What is a web framework? - (2012-11-10)
  [3705] Django Training Courses - UK - (2012-04-23)
  [3698] How to stop forms on other sites submitting to your scripts - (2012-04-15)
  [3640] Sessions (Shopping Carts) in Django - the Python Web Framework - (2012-03-05)
  [3639] Demonstration of a form using Django - (2012-03-04)
  [3634] Defining database relations in your Django model - (2012-03-02)
  [3633] Nesting Templates in Django - (2012-03-02)
  [3624] Why do we need a Model, View, Controller architecture? - (2012-02-25)
  [3140] Django - separating the HTML from the view / model - (2011-01-20)
  [3138] Django - adding your own views, and then templating your views. - (2011-01-18)
  [1745] Moodle, Drupal, Django (and Rails) - (2008-08-08)


Back to
A time to be brave? We should ask for what is best for our area.
Previous and next
or
Horse's mouth home
Forward to
Training Classes - should the training company provide a system for each delegate to use?
Some other Articles
Training Classes - should the training company provide a system for each delegate to use?
A framework with python - Django - first steps
A time to be brave? We should ask for what is best for our area.
Melksham Weather - Warm and windy becoming colder and calmer
An image from a website that occasionally comes out as hyroglyphics
Virtual Hosting with Apache http server - an overall scheme, and avoiding common pitfalls
Lua, Tcl, Python; Worldwide training classes
4252 posts, page by page
Link to page ... 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86 at 50 posts per page


This is a page archived from The Horse's Mouth at http://www.wellho.net/horse/ - the diary and writings of Graham Ellis. Every attempt was made to provide current information at the time the page was written, but things do move forward in our business - new software releases, price changes, new techniques. Please check back via our main site for current courses, prices, versions, etc - any mention of a price in "The Horse's Mouth" cannot be taken as an offer to supply at that price.

Link to Ezine home page (for reading).
Link to Blogging home page (to add comments).

You can Add a comment or ranking to this page

© WELL HOUSE CONSULTANTS LTD., 2014: Well House Manor • 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01144 1225 708225 • FAX: 01144 1225 899360 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho

PAGE: http://www.wellho.net/mouth/3136_A-f ... steps.html • PAGE BUILT: Sun Mar 30 15:20:58 2014 • BUILD SYSTEM: WomanWithCat