0% found this document useful (0 votes)
48 views8 pages

Chapter 2 - Getting Started

Getting Started Django

Uploaded by

Lalindra Kumara
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
48 views8 pages

Chapter 2 - Getting Started

Getting Started Django

Uploaded by

Lalindra Kumara
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 8

7/3/2009 Chapter 2: Getting Started

About | Comment help | Contact us | Errata | Buy the print version on Amazon.com

The Django Book previous table of contents next

Chapter 2: Getting Started


Installing Django is a multi-step process, due to the multiple moving parts in modern Web development
environments. In this chapter, well walk you through how to install the framework and its few
dependencies.

Because Django is just Python code, it runs anywhere Python does including on some cell phones! But
this chapter just covers the common scenarios for Django installations. Well assume youre installing it
either on a desktop/laptop machine or a server.
1
Later, in Chapter 12, well cover how to deploy Django to a production site.

Installing Python
Django itself is written purely in Python, so the first step in installing the framework is to make sure you
have Python installed.

Python Versions
3
The core Django framework works with any Python version from 2.3 to 2.6, inclusive. Djangos optional GIS
(Geographic Information Systems) support requires Python 2.4 to 2.6.

If youre not sure which version of Python to install and you have complete freedom over the decision, pick
the latest one in the 2.x series: version 2.6. Although Django works equally well with any version from 2.3
to 2.6, the later versions of Python have performance improvements and additional language features you
might like to use in your applications. Plus, certain third-party Django add-ons that you might want to use
might require a version newer than Python 2.3, so using a later version of Python keeps your options open.
3
Django and Python 3.0

At the time of writing, Python 3.0 had been released, but Django didnt yet support it. Python
3.0 introduced a substantial number of backwards-incompatible changes to the language itself,
and, as a result, we expect most major Python libraries and frameworks, including Django, will
take a few years to catch up.

If youre new to Python and are wondering whether to learn Python 2.x or Python 3.x, our
advice is to stick with Python 2.x.

Installation
2
If youre on Linux or Mac OS X, you probably have Python already installed. Type python at a command
prompt (or in Applications/Utilities/Terminal, in OS X). If you see something like this, then Python is installed:

Python 2.4.1 (#2, Mar 31 2005, 00:05:10)


[GCC 3.3 20030304 (Apple Computer, Inc. build 1666)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
djangobook.com/en/2.0/chapter02/ 1/8
7/3/2009 Chapter 2: Getting Started
>>>

Otherwise, youll need to download and install Python. Its fast and easy, and detailed instructions are
available at http://www.python.org/download/

Installing Django
At any given time, two distinct versions of Django are available to you: the latest official release and the
bleeding-edge trunk version. The version you decide to install depends on your priorities. Do you want a
stable and tested version of Django, or do you want a version containing the latest features, perhaps so
you can contribute to Django itself, at the expense of stability?

Wed recommend sticking with an official release, but its important to know that the trunk development
version exists, because youll find it mentioned in the documentation and by members of the community.

Installing an Official Release


1
Official releases have a version number, such as 1.0.3 or 1.1, and the latest one is always available at
http://www.djangoproject.com/download/.
3
If youre on a Linux distribution that includes a package of Django, its a good idea to use the distributors
version. That way, youll get security updates along with the rest of your system packages.

If you dont have access to a prepackaged version, you can download and install the framework manually.
To do so, first download the tarball, which will be named something like Django-1.0.2-final.tar.gz. (It
doesnt matter which local directory you download this file into; the installation process will put Djangos
files in the right place.) Then, unzip it and run setup.py install, as you do with most Python libraries.

Heres how that process looks on Unix systems:

1. tar xzvf Django-1.0.2-final.tar.gz


5
2. cd Django-*
2
3. sudo python setup.py install

On Windows, we recommend using 7-Zip (http://www.djangoproject.com/r/7zip/) to unzip .tar.gz files.


Once youve unzipped the file, start up a DOS shell (the Command Prompt) with administrator privileges
and run the following command from within the directory whose name starts with Django-:

python setup.py install

In case youre curious: Djangos files will be installed into your Python installations site-packages directory
a directory where Python looks for third-party libraries. Usually its in a place like
/usr/lib/python2.4/site-packages.

Installing the Trunk Version


The latest and greatest Django development version is referred to as trunk, and its available from Djangos
Subversion repository. You should consider installing this version if you want to work on the bleeding edge,
or if you want to contribute code to Django itself.

Subversion is a free, open source revision-control system, and the Django team uses it to manage changes
to the Django codebase. You can use a Subversion client to grab the very latest Django source code and,
at any given time, you can update your local version of the Django code, known as your local checkout, to
get the latest changes and improvements made by Django developers.

djangobook.com/en/2.0/chapter02/ 2/8
7/3/2009 Chapter 2: Getting Started
2
When using trunk, keep in mind theres no guarantee things wont be broken at any given moment. With
that said, though, some members of the Django team run production sites on trunk, so they have an
incentive to keep it stable.

To grab the latest Django trunk, follow these steps:


1
1. Make sure you have a Subversion client installed. You can get the software free from
http://subversion.tigris.org/, and you can find excellent documentation at
http://svnbook.red-bean.com/.

(If youre on a Mac with OS X 10.5 or later, youre in luck; Subversion should already be
installed. You can verify this by typing svn --version in the Terminal.)

2. Check out the trunk using the command


svn co http://code.djangoproject.com/svn/django/trunk djtrunk.
1
3. Locate your Python installations site-packages directory. Usually its in a place like
/usr/lib/python2.4/site-packages. If you have no idea, type this command from a
command prompt:

python -c 'import sys, pprint; pprint.pprint(sys.path)'

The resulting output should include your site-packages directory.

# Within the site-packages directory, create a file called


django.pth and edit it to contain the full path to your djtrunk directory to it. For
example, the file could just contain this line:

/home/me/code/djtrunk

1. Place djtrunk/django/bin on your system PATH. This directory includes management


utilities such as django-admin.py.

Tip:

If .pth files are new to you, you can learn more about them at
http://www.djangoproject.com/r/python/site-module/.

After downloading from Subversion and following the preceding steps, theres no need to run
python setup.py install youve just done the work by hand!
1
Because the Django trunk changes often with bug fixes and feature additions, youll probably want to
update it every once in a while. To update the code, just run the command svn update from within the
djtrunk directory. When you run that command, Subversion will contact http://code.djangoproject.com,
determine whether any of Djangos code has changed, and update your local version of the code with any
changes that have been made since you last updated. Its quite slick.

Finally, if you use trunk, you should know how to figure out which version of trunk youre running. Knowing
your version number is important if you ever need to reach out to the community for help, or if you submit
improvements to the framework. In these cases, you should tell people the trunk version, also known as a
revision number or changeset, that youre using. To find out your revision number, type svn info from
djangobook.com/en/2.0/chapter02/ 3/8
7/3/2009 Chapter 2: Getting Started
within the djtrunk directory, and look for the number after Revision:. This number is incremented each
time Django is changed, whether through a bug fix, feature addition, documentation improvement or
anything else. Among some members of the Django community, its a badge of honor to be able to say,
Ive been using Django since [insert very low revision number here].

Testing the Django installation


For some post-installation positive feedback, take a moment to test whether the installation worked. In a
command shell, change into another directory (e.g., not the directory that contains the django directory)
and start the Python interactive interpreter by typing python. If the installation was successful, you should
be able to import the module django:

>>> import django


>>> django.VERSION
(1, 1, 0, final, 1)

Interactive Interpreter Examples

The Python interactive interpreter is a command-line program that lets you write a Python
program interactively. To start it, run the command python at the command line.

Throughout this book, we feature example Python interactive interpreter sessions. You can
recognize these examples by the triple greater-than signs (>>>), which designate the
interpreters prompt. If youre copying examples from this book, dont copy those greater-than
signs.

Multiline statements in the interactive interpreter are padded with three dots (...). For
example:

>>> print """This is a


... string that spans
... three lines."""
This is a
string that spans
three lines.
>>> def my_function(value):
... print value
>>> my_function('hello')
hello

Those three dots at the start of the additional lines are inserted by the Python shell theyre
not part of our input. We include them here to be faithful to the actual output of the
interpreter. If you copy our examples to follow along, dont copy those dots.

Setting Up a Database
At this point, you could very well begin writing a Web application with Django, because Djangos only hard-
and-fast prerequisite is a working Python installation. However, odds are youll be developing a database-
driven Web site, in which case youll need to configure a database server.
1
If you just want to start playing with Django, skip ahead to the Starting a Project section but keep in
mind that all the examples in this book assume you have a working database set up.
djangobook.com/en/2.0/chapter02/ 4/8
7/3/2009 Chapter 2: Getting Started

Django supports four database engines:

PostgreSQL (http://www.postgresql.org/)
SQLite 3 (http://www.sqlite.org/)
3
MySQL (http://www.mysql.com/)
Oracle (http://www.oracle.com/)

For the most part, all the engines here work equally well with the core Django framework. (A notable
exception is Djangos optional GIS support, which is much more powerful with PostgreSQL than with other
databases.) If youre not tied to any legacy system and have the freedom to choose a database backend,
we recommend PostgreSQL, which achieves a fine balance between cost, features, speed and stability.

Setting up the database is a two-step process:

First, youll need to install and configure the database server itself. This process is beyond the scope of
this book, but each of the four database backends has rich documentation on its Web site. (If youre
on a shared hosting provider, odds are that theyve set this up for you already.)
Second, youll need to install the Python library for your particular database backend. This is a third-
party bit of code that allows Python to interface with the database. We outline the specific, per-
database requirements in the following sections.
2
If youre just playing around with Django and dont want to install a database server, consider using
SQLite. SQLite is unique in the list of supported databases in that it doesnt require either of the above
steps, if youre using Python 2.5 or higher. It merely reads and writes its data to a single file on your
filesystem, and Python versions 2.5 and higher include built-in support for it.
2
On Windows, obtaining database driver binaries can be frustrating. If youre eager to jump in, we
recommend using Python 2.5 and its built-in support for SQLite.

Using Django with PostgreSQL


2
If youre using PostgreSQL, youll need to install either the psycopg or psycopg2 package from
http://www.djangoproject.com/r/python-pgsql/. We recommend psycopg2, as its newer, more actively
developed and can be easier to install. Either way, take note of whether youre using version 1 or 2; youll
need this information later.

If youre using PostgreSQL on Windows, you can find precompiled binaries of psycopg at
http://www.djangoproject.com/r/python-pgsql/windows/.

If youre on Linux, check whether your distributions package-management system offers a package called
python-psycopg2, psycopg2-python, python-postgresql or something similar.

Using Django with SQLite 3


If youre using Python version 2.5 or higher, youre in luck: no database-specific installation is required,
because Python ships with SQLite support. Skip ahead to the next section.

If youre working with Python 2.4 or older, youll need SQLite 3 not version 2 from
http://www.djangoproject.com/r/sqlite/ and the pysqlite package from
http://www.djangoproject.com/r/python-sqlite/. Make sure you have pysqlite version 2.0.3 or higher.

On Windows, you can skip installing the former (the separate SQLite binaries), because theyre statically
linked into the pysqlite binaries.
4
djangobook.com/en/2.0/chapter02/ 5/8
7/3/2009 Chapter 2: Getting Started
4
If youre on Linux, check whether your distributions package-management system offers a package called
python-sqlite3, sqlite-python, pysqlite or something similar.

1
Using Django with MySQL
4
Django requires MySQL 4.0 or above. The 3.x versions dont support nested subqueries and some other
fairly standard SQL statements.

Youll also need to install the MySQLdb package from http://www.djangoproject.com/r/python-mysql/.

If youre on Linux, check whether your distributions package-management system offers a package called
python-mysql, python-mysqldb, mysql-python or something similar.

Using Django with Oracle


Django works with Oracle Database Server versions 9i and higher.

If youre using Oracle, youll need to install the cx_Oracle library, available at http://cx-
oracle.sourceforge.net/. Use version 4.3.1 or higher, but avoid version 5.0 due to a bug in that version of
the driver.

Using Django Without a Database


1
As mentioned earlier, Django doesnt actually require a database. If you just want to use it to serve
dynamic pages that dont hit a database, thats perfectly fine.

With that said, bear in mind that some of the extra tools bundled with Django do require a database, so if
you choose not to use a database, youll miss out on those features. (We highlight these features
throughout this book.)

Starting a Project
Once youve installed Python, Django and (optionally) your database server/library, you can take the first
step in developing a Django application by creating a project.

A project is a collection of settings for an instance of Django, including database configuration, Django-
specific options and application-specific settings.

If this is your first time using Django, youll have to take care of some initial setup. Create a new directory
to start working in, perhaps something like /home/username/djcode/.

Where Should This Directory Live?

If your background is in PHP, youre probably used to putting code under the Web servers
document root (in a place such as /var/www). With Django, you dont do that. Its not a good
idea to put any of this Python code within your Web servers document root, because in doing
so you risk the possibility that people will be able to view your raw source code over the Web.
Thats not good.

Put your code in some directory outside of the document root.

1
Change into the directory you created, and run the command django-admin.py startproject mysite. This
will create a mysite directory in your current directory.
4

djangobook.com/en/2.0/chapter02/ 6/8
7/3/2009 Chapter 2: Getting Started
Note
django-admin.py should be on your system path if you installed Django via its setup.py utility.

If youre using trunk, youll find django-admin.py in djtrunk/django/bin. Because youll be using
django-admin.py often, consider adding it to your system path. On Unix, you can do so by
symlinking from /usr/local/bin, using a command such as
sudo ln -s /path/to/django/bin/django-admin.py /usr/local/bin/django-admin.py. On
Windows, youll need to update your PATH environment variable.

If you installed Django from a packaged version for your Linux distribution, django-admin.py
might be called django-admin instead.

1
If you see a permission denied message when running django-admin.py startproject, youll need to
change the files permissions. To do this, navigate to the directory where django-admin.py is installed (e.g.,
cd /usr/local/bin) and run the command chmod +x django-admin.py.
3
The startproject command creates a directory containing four files:

mysite/
__init__.py
manage.py
settings.py
urls.py

1
These files are as follows:

__init__.py: A file required for Python to treat the mysite directory as a package (i.e., a group of
Python modules). Its an empty file, and generally you wont add anything to it.
manage.py: A command-line utility that lets you interact with this Django project in various ways. Type
python manage.py help to get a feel for what it can do. You should never have to edit this file; its
created in this directory purely for convenience.
settings.py: Settings/configuration for this Django project. Take a look at it to get an idea of the types
of settings available, along with their default values.
urls.py: The URLs for this Django project. Think of this as the table of contents of your Django-
powered site. At the moment, its empty.
1
Despite their small size, these files already constitute a working Django application.

Running the Development Server


For some more post-installation positive feedback, lets run the Django development server to see our
barebones application in action.
1
The Django development server (also called the runserver after the command that launches it) is a built-
in, lightweight Web server you can use while developing your site. Its included with Django so you can
develop your site rapidly, without having to deal with configuring your production server (e.g., Apache) until
youre ready for production. The development server watches your code and automatically reloads it,
making it easy for you to change your code without needing to restart anything.

To start the server, change into your project directory (cd mysite), if you havent already, and run this
command:

djangobook.com/en/2.0/chapter02/ 7/8
7/3/2009 Chapter 2: Getting Started
python manage.py runserver

Youll see something like this:

Validating models...
0 errors found.

Django version 1.0, using settings 'mysite.settings'


Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

1
This launches the server locally, on port 8000, accessible only to connections from your own computer. Now
that its running, visit http://127.0.0.1:8000/ with your Web browser. Youll see a Welcome to Django
page shaded in a pleasant pastel blue. It worked!

One final, important note about the development server is worth mentioning before proceeding. Although
this server is convenient for development, resist the temptation to use it in anything resembling a
production environment. The development server can handle only a single request at a time reliably, and it
has not gone through a security audit of any sort. When the time comes to launch your site, see Chapter
12 for information on how to deploy Django.

Changing the Development Servers Host or Port

By default, the runserver command starts the development server on port 8000, listening only
for local connections. If you want to change the servers port, pass it as a command-line
argument:

python manage.py runserver 8080

By specifying an IP address, you can tell the server to allow non-local connections. This is
especially helpful if youd like to share a development site with other members of your team.
The IP address 0.0.0.0 tells the server to listen on any network interface:

python manage.py runserver 0.0.0.0:8000

When youve done this, other computers on your local network will be able to view your Django
site by visiting your IP address in their Web browsers, e.g., http://192.168.1.103:8000/ . (Note
that youll have to consult your network settings to determine your IP address on the local
network. Unix users, try running ifconfig in a command prompt to get this information.
Windows users, try ipconfig.)

Whats Next?
Now that you have everything installed and the development server running, youre ready to learn the
basics of serving Web pages with Django.

C opyright 2006, 2007, 2008, 2009 Adrian Holovaty and Jacob Kaplan-Moss. previous table of contents next
This work is licensed under the GNU Free Document License.
Hosting graciously provided by

djangobook.com/en/2.0/chapter02/ 8/8

You might also like