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


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

Omar Zabaneh

July 25, 2008
Zeth, Thank you for this post, very helpful. I used it as a basis for my own email validation function that i wish to share with you, in a selfish ...
Email Syntax Check in Python

Double Booting Bastard

July 24, 2008
I agree with Nui, Linux is great for many things but not everything. A lot of, less mainstream, hardware is a time consuming and often fruitless task to install and ...
Give Linux a chance

John

July 23, 2008
Duncan, sadly the permissions are stored with the data (inode), not with the directory entries (hard-links). Zeth needs ACLs -- no way to do this with basic unix permissions.
Advanced Unix Groups

Garrick

July 21, 2008
I do love my iPhone. That being said, I would trade it in a heartbeat for a STABLE Openmoko FreeRunner.
This week - iPhone vs a can of compressed air, and Django NewFormsAdmin

Daniel Davies

July 21, 2008
With regards to your last paragraph, you are certainly correct. Right now Django is a nightmare to use across multiple sites... we have some sites running the newformsadmin branch, others ...
This week - iPhone vs a can of compressed air, and Django NewFormsAdmin

Nui

July 18, 2008
Hmm, this would be more persuasive as an argument with some evidence. I am a happy admin of Windows and a novice user of Linux, so I have taken the ...
Give Linux a chance

Paddy3118

July 18, 2008
Hi, I too work with Electronic Design Automation tools, where Tcl is used extensively. I tend to only occasionally have to write in Tcl and so find the TclTutor utility: ...
Python and TCL

Cliff Wells

July 17, 2008
I personally cannot live without the Web Developer extension or Firebug. Unfortunately these are probably both among the more difficult to port extensions. Given how poorly Firefox functions on Linux ...
Will Epiphany be able to compete with Firefox's extensions?

Åke Forslund

July 13, 2008
I'm pretty much a novice in both of these languages but I find them both easy to use and preform the tasks I give them. However I rarely use them ...
Python and TCL

Christopher Thoday

July 12, 2008
A single test is not sufficient to give you confidence that the algorithm is working. You should make 'number' an argument of 'main' so that you can test some boundary ...
Python and TCL

paul21

July 10, 2008
Shame on Mozilla. They should make developers specify the extension license before hosting it. They should show the license next to download button as well.
Are your Firefox extensions proprietary software?

Tris

July 8, 2008
Justin - You say they had not heard of Linux? That doesn't sound very professional to me!
Give Linux a chance

michael

July 8, 2008
what about Galeon? in Gnome i use Galeon mostly. it is fast and stable and has a nice portal with search masks for Debian, FSF, Freshmeat and so on. wtf ...
Will Epiphany be able to compete with Firefox's extensions?

vermin

July 7, 2008
> Eventually, after a bit of digging and Googling, I found their Toolbar-License... You simply found the license of the StumbleUpon Toolbar for Internet Explorer. This is another product, much ...
Are your Firefox extensions proprietary software?

Andrew West

July 6, 2008
Both the Python and the Tcl example could do with error checking. While at first this may not seem on topic with the post I think it better shows the ...
Python and TCL