C H A P T E R   1

image

Welcome to Django

Web development is hard, and don't let anybody tell you otherwise. Building a fully functional, dynamic web application with all the features that users want is a daunting task with a seemingly endless list of things you have to get just right. And before you can even start thinking about most of them, you must do a huge amount of up-front work: set up a database, create all the tables to store your data, plan out all the relationships and queries, come up with a solution for dynamically generating the HTML, figure out how to map specific URLs to different bits of code, and more. Just getting to the point where you can add features your users will see or care about is a vast and largely thankless job.

But it doesn't have to be that way.

This book will teach you how to use Django, a “web framework” that will significantly ease the pain of embarking on new development projects. You'll be able to follow along as you build real-world applications, and at every step you'll see how Django is there to help you out. At the end, you'll come to a wonderful realization—that web development is fun again.

What's a Web Framework and Why Should I Want One?

The biggest downside of web development is the sheer amount of tedium it involves. All the aforementioned up-front tasks plus dozens more lurk behind every new application you develop, and they quickly suck all the joy out of even the most exciting projects. Web frameworks such as Django aim to eliminate all that tedium by providing an organized, reusable set of common libraries and components that can do the heavy lifting, freeing you up to work on the features that make your project unique.

This idea of standardizing a set of common libraries to deal with common tasks is far from new. In fact, this standardization is such an established practice in most areas of programming that you'd get strange looks if you suggested somebody should just start writing code from scratch. And in enterprise web development, frameworks of various sorts have been in use for years. Most companies that routinely need to develop large-scale applications rely heavily on frameworks to provide common functionality and speed up their development processes.

But in the world of web development, frameworks have traditionally been—almost out of necessity—just as heavyweight as the applications in which they're used. They tend to be written in Java or C# and targeted at large corporate development projects, and sometimes they come with a price tag that only a Fortune 500 company could love. Django is part of a new generation of frameworks geared toward a broader audience: developers who don't necessarily have the weight of a multinational conglomerate's needs bearing down on their shoulders, but who still need to get things done quickly. In other words, Django targets developers like you and me.

The past couple years have seen the emergence of a number of these new web frameworks, written in and for programming languages that are much more accessible to the average web developer (and, just as importantly, to the average web host): PHP, Perl, Python, and Ruby. Each framework has a slightly different philosophy regarding code organization and the number of “extras” it includes, but they all share a common baseline goal: to provide an integrated, easy-to-use set of components that handle the tedious, repetitive tasks of web development with as little fuss as possible.

Saying Hello to Django

Django began life as a simple set of tools used by the in-house web team of a newspaper company in a small college town in Kansas. Like anybody who spends enough time doing web development, they got tired of writing the same kinds of code over and over again—database queries, templates, the whole nine yards. They grew weary of this quickly, in fact, because they were pressured to keep up with a tight newsroom schedule. Needing custom code for a big story or feature wasn't (and still isn't) unusual, and the development timelines needed to be measurable in days, or even hours, to keep pace with the news.

In the space of a couple years, they developed a set of libraries that worked extremely well together. By automating or simplifying the common tasks of web development, the libraries helped them get their work done quickly and efficiently. In the summer of 2005, they got permission from the newspaper's managers to release those libraries publicly, for free, under an open source license so that anyone could use and improve them. They also gave these libraries a snappy name, “Django,” in honor of the famous gypsy jazz guitarist Django Reinhardt.

As befits its newsroom heritage, Django bills itself as “the web framework for perfectionists with deadlines.” At its core is a set of solid, well-tested libraries covering all of the repetitive aspects of web development:

  • An object-relational mapper, which is a library that knows what your database looks like, what your code looks like, and how to bridge the gap between them without repetitive hand-written SQL
  • A set of HTTP libraries that knows how to parse incoming web requests; how to hand them to you in a standard, easy-to-use format; and how to turn the results of your code into well-formed responses
  • A URL routing library that lets you define exactly the URLs you want and map them to the appropriate parts of your code
  • A validation library that helps you display forms in web pages and process user-submitted data
  • A templating system that lets even nonprogrammers write HTML mixed with data generated by your code and just the right amount of presentational logic

And that's just scratching the surface. Django's core libraries include a wealth of other features you'll come to love. A number of useful applications that build on Django's features are also bundled with it and provide out-of-the-box solutions for specific needs such as administrative interfaces and user authentication. In the example applications used in this book, you'll see all of these features in action. So let's dive in.

Saying Hello to Python

Django is written in a programming language called Python, so the applications you develop with it will also be written in Python. That means you'll need to have Python installed on your computer before you can get started with Django. You can download Python for free from http://python.org/download/; it's available for all major operating systems. As I write this, the Python language is in the process of migrating from one series of major releases (with version numbers of the form “2.x”) to another (with version numbers of the form “3.x”). This process is expected to take several years, and most Python-based software, Django included, has not yet begun migrating to the new 3.x series. Thus it's best to install the latest 2.x version of Python—Python 2.6.1 at the time of this writing—in order to enjoy the latest features and bug fixes for the Python language while using Django.

Once you've installed Python, you should be able to open a command prompt (Command Prompt on Windows, Terminal on Mac OS X, or any terminal emulator on Linux) and start the Python interactive interpreter by typing the command python. Normally, you'll save your Python code into files that will run as part of your applications. But the interactive interpreter will let you explore Python—and Django, once it's installed—in a more freeform way: the interpreter lets you type in Python code, a line at a time, and see the results immediately. You can also use it to access and interact with code in your own Python files, code in the Python standard libraries, or code in any third-party libraries you've installed. This capability makes the interactive interpreter a powerful learning and debugging tool.

When you first fire up the Python interpreter, you'll see something like this:

Python 2.6.1 (r261:67515, Apr 2 2009, 01:36:23)
[GCC 4.0.1 (Apple Computer, Inc. build 5488)] on darwin
Type “help”, “copyright”, “credits” or “license” for more information.
>>>

The >>> is Python's command prompt. You can type a line of Python code and press Enter, and if that code returns a result, you'll see it immediately. To test this, try a simple line that prints some text. Open the Python interpreter, type the following line at the prompt, and then press the Enter key:

>>> print “Hello, world!”

You'll see the result appear on the next line:

Hello, world!
>>>

Anything you can type into a file as part of a Python program can be typed directly into the interpreter. You can also access the built-in help system by typing help() and pressing Enter. When you're ready to exit the Python interpreter, press Ctrl+D to shut it down.

Installing Django

Now that you've got Python installed and working, it's time to install Django and start exploring its features. You can get a copy from the official Django web site; visit www.djangoproject.com/download/ and follow the instructions for downloading the latest official release (which should be Django 1.1 by the time this book goes to press).

Once you've downloaded the Django code onto your computer, you can install it by typing a single command. On Linux or Mac OS X, open a terminal, navigate to the directory where Django was downloaded, and locate a file named setup.py. Type the following command, and enter your password when prompted:

sudo python setup.py install

On Windows, you'll need to open a command prompt with administrative privileges. Then you can navigate to the Django directory and type the following:

python setup.py install

The setup.py script is a standard installation procedure for Python modules, and it takes care of installing all the relevant Django code into the correct locations for your operating system. If you're curious, Table1-1 summarizes where the Django code will end up on various systems.

Django Installation Locations

Operating System Django Location
Linux /usr/local/lib/python2.6/site-packages/django
Mac OS X /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.5/site-packages/django
Windows C:Pythonsite-packagesdjango

Taking Your First Steps with Django

You should now be able to verify that Django installed correctly on your computer. Next, start the interactive Python interpreter and type in the following:

>>> import django
>>> print django.VERSION

Running these commands should display a set of numbers in parentheses, which represents the version of Django you're using. The Django 1.1 release, for example, will show (1, 1, 0, ‘final’, 0). Python software typically uses a version tuple—a parenthesized, comma-separated list of numbers and/or words—to represent version numbers internally, and Django is no different. (This version tuple makes it easy for Python programs to automatically parse otherwise complex version numbers such as “1.0 beta 3” or “2.4 prerelease.”)

Now you're ready to create your first Django project. A Django project is a wrapper of sorts, which contains a list of one or more Django-powered applications and the settings they use. Later on, when you're deploying your Django applications behind a real web server, you'll use projects to configure them.

To set up your first project, create a directory on your computer where you'll keep your in-progress Django projects, and then navigate to it using a terminal or a command prompt. It's often a good idea to have a single directory where you keep all of your own custom Python code, so choose a single logical place on your computer for this. As you'll see a bit later, doing so will simplify the process of telling Python how to find and use that code.

Now you can use the built-in Django management script, django-admin.py, to create your project. django-admin.py lives in the bin/ subdirectory of the directory Django was installed into, and it knows how to handle various management tasks involving Django projects. The command you're interested in is called startproject, which will create a new, empty Django project. In the directory where you want to create your project, type the following (refer to Table1-1 for the correct path for your operating system):

/usr/local/lib/python2.6/site-packages/django/bin/django-admin.py startproject cms

This will create a new subdirectory called cms and populate it with the basic files needed by any Django project. (You'll see why it's named cms in the next chapter, when you start to work with this project.)

In the next section, you'll see what each of the files in the project directory is for, but focus on manage.py for now. Like django-admin.py, the manage.py script takes care of common project- and application-management tasks for you. For example, it can start a simple web server that will host your project for testing purposes. You can start the manage.py script by going into your project directory and typing the following:

python manage.py runserver

Then you should be able to open a web browser and visit the address http://127.0.0.1:8000/. By default, the development web server runs on your computer's local “loopback” network address, which is always 127.0.0.1, and binds to port 8000. When you visit that address, you should see a simple page saying “It worked!” with some basic instructions for customizing your project (see Figure 1-1).

image

Figure 1-1. Django welcome screen

You can stop the server by pressing Ctrl+C at the command prompt.

Exploring Your Django Project

The startproject command of django-admin.py created your project directory for you and automatically filled in a few files. Here's a quick primer on these files, all of which I'll explain further in future chapters:

__init__.py: This will be an empty file. For now you don't need to put anything into it (and in fact, most of the time you won't need to). It's used to tell Python that its directory contains executable code. Python can treat any directory containing an __init__.py file as a Python module.

manage.py: As I explained previously, this is a helper script that knows how to handle common management tasks. It knows how to start the built-in development web server, create new application modules, set up your database, and do numerous other things that you'll see as you build your first Django applications.

settings.py: This is a Django settings module, which holds the configuration for your Django project. Over the next few chapters, you'll see some of the most common settings and how to edit them to suit your projects.

urls.py: This file contains your project's master URL configuration. Unlike some languages and frameworks that simply mimic HTML by letting you place code into the web server's public directory and access it directly by file name, Django uses an explicit configuration file to lay out which URLs point to which parts of your code. This file defines the set of “root” URLs for an entire project.

You might notice that after you started the built-in web server, one or more new files appeared in the project directory with the same names as those in the preceding list but with a .pyc extension instead of a .py extension. Python can read the code directly out of your .py files, but it also can, and often does, automatically compile code into a form that's faster to load when a program starts up. This bytecode, as it's called, is then stored in identically named .pyc files. If the original file hasn't changed since the last time a program used it, Python will load from the bytecode file instead of the original file to gain a speed boost.

Looking Ahead

In the next chapter, you'll walk through setting up your first real Django project, which will provide a simple content management system, or CMS. If you're ready to dive in, keep reading, but you should also feel free to pause and explore Python or Django a bit more on your own. Both the django-admin.py and manage.py scripts accept a help command, which will list all of the things they can do. Plus, the Python interpreter's built-in help system can also automatically extract documentation from most Python modules on your computer, including the ones inside Django. There's also a special shell command to manage.py that you might find helpful: it uses your project's settings module to launch a Python interpreter with a fully configured Django environment that you can explore.

If you'd like, you can also take this opportunity to set up a database to use with Django. If you installed Python 2.5 or any later version, you won't have to do this right away. As of version 2.5, Python includes the lightweight SQLite database system directly, which you'll be able to use throughout this book as you develop your first applications. However, Django also supports MySQL, PostgreSQL, and Oracle databases, so if you'd prefer to work with one of those, go ahead and set it up.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset