• Zeth will be attending PyCon UK on the 12th to 14th September 2008.

Baby Steps with Django - Part 3 Django projects

2 February 2008

Projects and Applications

In theory, as long as Python can find everything, you can organise your own web application code however you want; however, we might as well follow the default Django way until we have a good reason not to. A Django website is normally organised into a 'project' which contains 'applications'.

A project has a database, most small to medium websites will only need one database so therefore will only need one project. Of course, the web server (i.e. Apache) can host many Django projects under a single domain name, but for now we will assume that we have just one project for this website.

So under the project we have applications. These provide the dynamic and interactive functionality of the web site. These are the fun bits! We might have, for example, stories, comments, quizzes, rss feeds, or whatever else you can think of. Each of these things can be a separate application.

Starting a project

So in the last post we got a database ready and installed Django to the system. Now we want to create a project:

django-admin.py startproject mysite

You may need to leave out the .py depending on your distribution and how you got Django. The command that works is the correct one!

django-admin startproject mysite

This command creates a directory with four files inside. Two are fluff that we do not edit:

__init__.py is just a stub that lets the Python interpreter view the directory as a Python package.

manage.py is a tool that provides some friendly command line abstractions of Django features.

The remaining two files are the interesting ones.

urls.py

urls.py contains your URL mappings, i.e. it maps the URLs to the applications. This is also sometimes called 'request dispatching'. This function is called routes in Pylons and Ruby on Rails.

What does this mean? Well a 1990s-style static website will just be 'piles of files'. When the request comes in, the webserver will return a file, end of story. No logic is involved.

URL mapping is what distinguishes a 21st Century dynamic web application from that. When the request comes in, the relevant code will run and then a webpage will be generated and returned with a pretty URL that looks however you want.

So for example, let's imagine a Django powered blog. In this case, a user requests the URL http://some.where/feeds/ which is then handled by the feeds application which generates an RSS feed of the latest posts.

Your urls.py is rather empty at the moment, but in a completed Django website, urls.py may have a number of lines that look something like this:

(r'^feeds/$', 'mysite.feeds'),

The first half is a regular expression, the second part is the application that is handling the request. So if the URL matches the first part, then the application on the right is in charge. The urls.py directives will be more complicated in a real-life examples of course.

If you are confused by the first part, don't worry too much at this point. For the sake of completeness, r means that the string should be interpreted by Python as a raw string (i.e. don't escape n and so on). ^ and $ are Python regular expression syntax for the start and end of the string.

settings.py

The file settings.py, as you might have guessed, is your project's settings, such as the database settings, what applications you have installed, what your time zone is, where your static files are and so on. It is just a simple config file. It a basic python file not .ini format, so remember the quote marks around strings or you will get errors. For example:

TIME_ZONE = 'Europe/London'

Add your database information to settings.py now using the four pieces of information that you recorded in the last post. It should look something like this:

DATABASE_ENGINE = 'mysql'

DATABASE_NAME = 'djtest'

DATABASE_USER = 'djangouser'

DATABASE_PASSWORD = 'password'

Now we will create the initial database tables, the following command syncs the database to match the current state of our project.

python manage.py syncdb

Since this is the first time we have run it in this project, it will give you the choice of creating a superuser account. Accept it and take note of what you have entered, you will need it later.

Now we are ready to create applications. We will leave that for the next post. In the meantime, you might want to test your project by running the test server:

python manage.py runserver 8080

In your web-browser, enter the URL http://127.0.0.1:8080/

With a bit of luck you will get the Django welcome screen telling you that Django works.

Discuss this post - leave a comment

1 dbr says...

Not sure if it's been suggested to you in the either of the other two parts, but: Have you looked at the web.py framework?

A while ago I looked at a few web-dev frameworks. Django was the biggest I found (TurboGears was the other, but I've not got around to playing with it yet)

I really disliked Django. It seemed to rely on magically knowing and remembering what a bunch of unintuitive "middleware" scripts did. After going though a bunch of tutorials and guides on it, I kind of gave up on it.

I found web.py much much more intuitive. Only once did I have to look up how to do something in web.py (How to retrieve the request's remote-IP - ip=web.ctx['ip'] )

The structure is a regular class, with a function named "GET" which is called for HTTP GET requests, and the same for "POST".

The URLs -> class mapping is done by a urls tuple, much like Django.

Then what ever you print() in that function gets output as HTML. And that's about as complicated as it gets..

The "hello world" for it is:

## start ##
import web # import web.py

urls=("^/hi/([a-zA-Z]+)$","helloworld") # map /hi/bob to helloworld class

class helloworld:
    def GET(self, name): # handle GET requests
    print name # Outputs the supplied name (bob from the URL /hi/bob
   # end GET
# end helloworld

if <em>*name*</em> == "<em>*main*</em>":
    web.run(urls) # starts development server if run directly
## end ##

To start the development server, you run "python the-script.py"

There is a tempting system included - and with a reasonable database API (SQLObject is suggested I think) that's pretty much all I needed.

I find web.py more Python'y, and Django is basically "Ruby on Rails in Python"

It may be worth playing with? The site for web.py is http://webpy.org - which is currently down just now... If all else fails and you're interested, I could upload the version I have from a while ago

http://www.sitepoint.com/blogs/2006/01/06/a-simple-wiki-with-webpy/ is an example site made in web.py (And I think reddit.com is or was created using web.py too)

And I think that's about enough rambling on about web.py..

Posted at 3:09 p.m. on February 2, 2008


2 Albert says...

Thanks for posting this - I'm still taking baby steps with python and could use a tutorial like this.

Posted at 2:49 a.m. on February 12, 2008


What do you have to say?

Show Editing Help


PyCon UK

About

Hello, my name is Zeth, I'll be your host here.

Command Line Warriors is about taking control of your own technology, it looks at our experiences of computing; especially using GNU/Linux, the Python programming language, the command-line and issues such as techno-ethics, best practices and whatever is cool now. If you take control of your technology then you are a Warrior too!

This site is your site too which means that you can contribute and get involved. You can leave comments using the facility provided. For me, the comments and discussions are by far the best part of the site. So please do have your say!

Latest Discussions

deesha

September 8, 2008
hey all, i just wanted to check the other stuf if nay1 can help me what i want is i have to convert the line starting with my function name ...
Email Syntax Check in Python

Daniel Black

September 3, 2008
Hey, sounds good already. There's another Python script for command-line 140-character-messaging (won't call it "tweeting" for obvious reasons), Tweety Py, that's currently languishing. Not, I think, because the developer's disinterested, ...
Using new social networking service Identi.ca from the command line

Antonio Araujo

September 2, 2008
Dear friends, has anyone built debian packages of db xml 2.4.13? Best regards Antonio
Native XML storage with Berkeley DB XML - part one

Zeth

September 1, 2008
Thanks everyone for your different solutions, absolutely fantastic. I have tried them all. The one from Ciaran McCreesh was the one I was subconsciously groping for.
Sisu and typing unicode in GNOME

andylockran

September 1, 2008
In ubuntu, I do ctrl, and the functions to the right of my keyboard for extra characters. Such as: alt gr + ; + e for é I'll post more ...
Sisu and typing unicode in GNOME

Jinks

September 1, 2008
I am from Germany but i use an US-layout keyboard since that's a lot easier for most my programming needs. Now, having to also write the occassional german letter or ...
Sisu and typing unicode in GNOME

Toni

September 1, 2008
Hi, You might want to add an xkb keymap. Make backups before you begin ;) And sorry about formatting. in /usr/share/X11/xkb/symbols/gb, after "intl", add this: partial alphanumeric_keys xkb_symbols "intl_fi" { ...
Sisu and typing unicode in GNOME

Ciaran McCreesh

September 1, 2008
On a UK keyboard you do alt-gr+[ followed by a to get ä. You don't need the control key at all.
Sisu and typing unicode in GNOME

name

September 1, 2008
Hi!,
List files recursively by modified time

name

September 1, 2008
Hello!,
List files recursively by modified time

Leif

September 1, 2008
On my Norwegian keyboard, the diaeresis is easily accessible, like on Jani's Finnish one. It's one of the few keys that doesn't advance the cursor, along with the tilde, circumflex ...
Sisu and typing unicode in GNOME

Lornix

September 1, 2008
ä <= compose, ", a ö <= compose, ", o å <= compose, o, a Ä <= compose, ", A Ö <= compose, ", O Å <= compose, o, A ...
Sisu and typing unicode in GNOME

name

September 1, 2008
Good day!,
List files recursively by modified time