Chapter 19. An Introduction to Django

If you have ever developed web applications, you are probably aware that it can oftentimes be a tedious task. To help ease this problem, some languages have turned to web application frameworks such as Ruby on Rails or Java's Spring Framework to handle some of the basic building blocks common to all web applications, leaving the programmer to concentrate on the more interesting aspects.

Nearly every language has at least one — and in many instances quite a few — frameworks, and Python is no exception. Built upon the Python language, Django is the standard web application framework used by Python developers who want to build for the Web on the fly.

You do not need to know web development to read this chapter, but it will certainly make things easier. At the bare minimum you should have a solid understanding of procedural programming, and be comfortable working with decision making (if statements and loops), as well as data storage through lists and hashes. If not, it might be worth going back and reviewing the previous chapters in this book.

In this chapter you learn:

  • To define what a framework is and explain why you would use one

  • To install the latest version of Django

  • To explain what the MVC/MTV Architecture is

  • To create views and templates in Django

  • To incorporate databases into your Django web applications

What Are Frameworks and Why Would I Use One?

Earlier I bandied about the term web application framework without really explaining what one was. To fully understand not only the what, but also the why of frameworks, it is essential to understand some of the core fundamentals that pretty much every web application/database-centric website must have as a foundation.

The first of the foundations is database connectivity. This is a vital part of any web application. It contains many records you may not even think about. Here is where you will store information like user name, permissions, settings, comments, profiles — the list goes on and on. Django supports quite a few databases (covered later in the chapter), some of which do and do not use SQL.

The second foundation is the administrative panel. An administrative panel gives the admin, and others, the ability to work with anything stored in the database. For instance, if you want to change a user's permissions from a registered user to a super administrator, you will need an admin panel.

Next up is the ability to leave comments. Despite the seemingly endless amount of useless comments that eat up acres of landscape on the Web, they are still a vital aspect of any well-designed website. They allow users to feel as though they are part of a community and not a lone voice whispering into the wind.

Another important feature of this type of site is user authentication. This controls how the users sign in, ensures secure logins, decides who has permission to do what on the site, and so forth.

You are not even halfway through the list of the tenants that dictate a well-thought-out web application, and as you can see, it is a lot to think about, and program. And let's face it — it's not very interesting. You have not even touched upon user-interfaces and design, which really should be the main focus of the site.

In the days before frameworks, a programmer would have to code all of the above and more by hand, eating up oodles of time, which in turn increases production costs. Fortunately for us, though, frameworks take care of the mundane aspects. All of the above, and more, can instantly be set up thanks to Django.

Other Features of Web Frameworks

In addition to what is listed in the preceding section, frameworks offer the following:

URL Mapping, Frameworks, and Django (in particular) — Interpret URLs so they are more friendly (and intuitive) to both the user, and more importantly, search engines and indexing. A good example of this is the URL: /mypage.cgi?cat=comic&topic=superman. The URL mapping feature would change this to a simpler address, such as /mypage/comic/superman. Visitors to your site are more likely to remember this URL if they want to automatically come to this page again, and it makes it easier for search engines to understand the underlying structure of your website.

Caching — Web caching is the process of storing a copy of a document. When this page is revisited, if certain criteria are met, the page is loaded from memory, instead of a new page being requested. This, in turn, increases the speed by which the page loads and the overall usability of the site.

Templating — A template gives a uniform look to a website, and serves many purposes. For one, it looks professional. Secondly, it ensures that users do not become confused and think that they have left your site. Next, it creates a seamless feel, so that every part of the site behaves in the manner you expect it to. For example, if clicking a print button on one page prints a document, the print button on every page will do the same thing, and will also appear in the same spot. Perhaps more importantly, templating can reduce the number of pages within a website. By having a "flat page," your site can access the database and grab certain data, displaying it in the page. A good way to think of this is to consider a website that lists author bios. If your site features 10,000 authors, in the old days you may have had to write 10,000 pages — one for each author. With templating, however, you have one "flat page" that reaches into the database and fills in the data for one of the 10,000 authors in the database. So essentially you now have one page that can dynamically act as many.

A full run-down of web frameworks and their features is beyond the scope of this book, but with the preceding information, you should have a pretty steady handle on the possibilities. It is certainly enough information to get you started using frameworks.

Django — How It All Began

Django, pronounced with a silent "d" and rhyming with Bang-o, was named after the gypsy jazz guitarist Django Reinhardt. It was created by a group of programmers at a little place called World Online, which at the time was the department responsible for web design for the Lawrence Journal-World newspaper in Kansas, among other properties.

Often forced to scramble to meet last-minute deadlines and asked to write new web apps on the fly, two men by the names of Adrian Holovaty and Simon Willison developed a new web framework to handle the demands of the editorial staff. Two years later, in 2005, the team joined up with Jacob Kaplan-Moss and released the framework to the open source community under the name of Django.

Because Django was originally built to handle the needs of several online newspapers, it has earned both the prestige and the stigma of being a "content" framework, good for publishers but little else. This, of course, is simply not true. Django is just as powerful and flexible as any other framework, as you will soon see.

For more information on the history and purpose behind Django, feel free to visit http://www.djangoproject.com/.

Installing Django

At the time of this writing, the current version of Django is 1.1. As with many libraries and components, it has not been upgraded to work with Python version 3.1. However, it does work with Python 2.6, and as such, you will be working with that version for the remainder of this chapter. If you do not have a copy of Python 2.6 installed, please install it at this time. It installs the same as version 3.1. You can find it at http://www.python.org/download/.

To install Django, go to http://www.djangoproject.com/download/. I suggest that you download the official version and steer clear of the latest development version. If you do decide to go with the development version, you probably do not need instructions on how to install it, so for the purposes of this chapter, you will use the latest version.

For Windows users, installation is fairly simple. Download the .tar.gz file and extract it to your Python26 folder (this is typically located at C:/Python26). Once the file has been unzipped, open up your command prompt (Start Menu

Installing Django
cd  C:Python26Django-1.1

Next, type in:

setup.py install

You will see the program installing and configuring a bunch of packages. Finally, it will finish, and Django will be officially installed. The install location, for the record, will be something along the lines of C:Python26Libsite-packages.

To test your installation, all you need to do is open up IDLE and type the following:

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

To install Django on non-Windows computers, such as Linux, Mac OS X, or other UNIX-based systems, download the tar.gz file and untar it with:

tar xzvf Django-1.0.0-final.tar.gz

Note that you will have to change the 1.0.0 to whatever version you have downloaded. Next, change the directory to the directory in which the file was untarred:

cd Django-1.0.0

where 1.0.0 is the version number. Finally, enter sudo python setup.py install in your command prompt, and wait for the magic to happen. To test that it is working, use the same method described earlier.

Understanding Django's Architecture

Before you begin developing your first Django project, let's touch upon one final aspect of web frameworks — namely, architecture. Most frameworks operate under the MVC architecture, or Model-View-Controller. Django is no different, though at times you will hear that it runs under an MTV, or Model-Template-View architecture, which, for me at least, is simply a matter of semantics.

For web application purposes, MVC architecture is best described by the following breakdown:

  • Model — The actual data or content that is displayed in the page and is stored in a database, XML node, or other area.

  • View — The web page, be it HTML, XHTML, or markup language.

  • Controller — The portion of code that collects the data from the model (database/xml) and passes it to the view (web page).

Though this may be a simplistic view, for your purposes, it is more than sufficient.

Initial Project Setup

Because this is your first time doing a Django project, you must do some things first. Note that a project in Django terms doesn't follow the typical sense of the word project. In Django, a project refers to the settings of an instance of Django, which is comprised of Django and application-specific settings as well as database options.

To start with, create a new directory. To do this, navigate to the location where a file called django-admin.py resides, which is usually in your site-packagesdjangoin directory. Here is what you type into your command prompt to change to that directory:

cd C:Python26Libsite-packagesdjangoin

Next, you need to run the django-admin.py file and tell it to create a new directory where your project and code will be stored. For the purposes here, call this new directory newsite. Type the following in your command prompt:

django-admin.py startproject newsite

Note that in the future you can change newsite to whatever you would like to call your directory.

Startproject is a command that creates not only a new directory, but stores four important files inside of it. They are:

  • __init__.py — This empty file allows Python to treat your directory (in this case newsite) as a package. You may remember that packages are nothing more than groups of Python modules.

  • manage.py — This is a command-line utility for interacting with Django projects.

  • settings.py — This file allows you to change the settings and general configuration of your project. Following is the code you will see if you open it in IDLE:

    # Django settings for newsite project.
    DEBUG = True
    TEMPLATE_DEBUG = DEBUG
    ADMINS = (
        # ('Your Name', '[email protected]'),
    )
    MANAGERS = ADMINS
DATABASE_ENGINE = ''           # 'postgresql_psycopg2', 'postgresql',
'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = ''             # Or path to database file if using sqlite3.
DATABASE_USER = ''             # Not used with sqlite3.
DATABASE_PASSWORD = ''         # Not used with sqlite3.
DATABASE_HOST = ''             # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = ''             # Set to empty string for default. Not used with sqlite3.

# Local time zone for this installation. Choices can be found here:

# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name

# although not all choices may be available on all operating systems.

# If running in a Windows environment this must be set to the same as your

# system time zone.

TIME_ZONE = 'America/Chicago'

# Language code for this installation. All choices can be found here:

# http://www.i18nguy.com/unicode/language-identifiers.html

LANGUAGE_CODE = 'en-us'

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not

# to load the internationalization machinery.
USE_I18N = True

# Absolute path to the directory that holds media.

# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = ''

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = ''

# URL prefix for admin media - - CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/media/'

# Make this unique, and don't share it with anybody.
SECRET_KEY = 'ms159e^bu=@m&grk106cl4kq&b058)*b4#01p69z@xop1y4zas'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.load_template_source',
    'django.template.loaders.app_directories.load_template_source',
#     'django.template.loaders.eggs.load_template_source',
)
MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
)

ROOT_URLCONF = 'newsite.urls'
TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/
templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

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

I discuss how to modify this file later on.

  • urls.py — This is where all of the URLs for your current Django project will be stored.

The final step to take before you can begin working with your first project is to set up the development server. The development server allows you to test your site and see its progress without having to set up your actual web server (you'll eventually need to do this when you are ready to have your site go live to the public.)

The first step to set up the server is to change your directory to the newsite:

cd C:Python26Libsite-packagesdjangoin
ewsite

Next, you will need run the manage.py file and give it the runserver command:

manage.py runserver

After a few seconds your command prompt will display the following:

Django version 1.1, using settings 'newsite.settings'
Development server is running at http"//127.0.0.1:8000/
Quit the server with CTRL-BREAK.
...

Your server is now set up to run locally. You can view the result by typing the following into your web browser's address bar: http://127.0.0.1:8000/. Note that this will only be visible from your computer, so do not expect outsiders to be able to view your page.

And that is all there is to it. Now you are finally ready to get your hands dirty!

Creating a View

You read about views earlier in the discussion on the Model-View-Controller architecture. As you will recall, in simple terms, the view is nothing more than an HTML or XHTML page. For the first few examples in this chapter, you are going to create the HTML inside of your Python code. This is purely for demonstrational purposes; in reality, your HTML would be inside of a templated page. But don't worry — I will cover that soon enough.

Working with Templates

Now that you understand the ways that views and URLconfs work, you can begin to work with templates. As stated previously, embedding HTML in your Python is not the best way to go about creating views. In this section, you learn to use templates instead.

Templates, in their simplest form, are a way to ensure consistency across a site. Using a template also saves time; you may recall the discussion about the 10,000 author bios?

Like an HTML document, templates are made up of many different tags — too numerous to cover here — as well as filters. As you continue through this section, I will try to cover the most important ones. These filters and tags control how the page looks, regardless of the data that is displayed in them. Think of them the way you would a school uniform; different students with different attributes all wear the same clothes, and therefore have a level of uniformity.

To see a template in action, open up your Command Prompt and navigate to the newsite folder (if you are not already there):

cd C:Python26Libsite-packagesdjangoin
ewsite

Next, run the following command:

manage.py shell

This command opens up the interactive interpreter. At this point you are probably wondering why you don't just use the IDLE editor, and it is a valid question. The reason you use the interactive interpreter, at least for now, is because it automatically sets your Django settings file for you. If you try to run the code in the next section in IDLE, it simply won't work. Later in the chapter, you learn how to edit your Django settings so that you can code wherever you like. For now, though, you are going to let the manage.py shell do all of your work for you.

For your first step, you need to import the template system. You do this like so:

>>>from django import template

Now you are going to create a template object. In this case, you want to create an object that will eventually hold a book title:

>>>btitle = template.Template('Your book is titled {{ book }}.')

The next bit of code will actually fill or give context to your template object:

>>> a = template.Context({'book': 'American Gods'})

Within the template object is a method called render(), which returns the rendered template as a string, evaluating every variable and template tag in the proper context. Here is how you use it:

>>>print btitle.render(a)
Your book is titled American Gods.

Using Templates and Views

Now that you know how to use views, modify your URLconfs, and create templates, you can use your view and template together, instead of embedding the HTML directly in your code.

Before you do, however, I just want to make a quick note: Django templates are not a mandatory part of the system. Python provides its own set of templates. However, Django's built-in templating system is pretty flexible and powerful, so you might want to strongly consider using it instead.

Models

You may recall the conversation about Django having an MVC (Model-View-Controller) architecture. As stated, sometimes Django's architecture is referred to as MTV (Model-Template-View). Most people in the Django community will agree that both are correct. In either case, so far you have viewed both the View and Template portion of Django's architecture, leaving you with only one further aspect: the Model.

Simply put, a model in Django describes the data that is held in your database. This description gives you information on how to access the data, the various relationships in the database, and how to validate your data. Another way to look at it is to think of it as an SQL Create Statement, only a little more defined. This added definition comes courtesy of the way Django creates tables; it does so through Python code instead of SQL (note that Django does use SQL code, but the data structures that it returns are all Python).

An example of this extra definition would be how most databases that work on SQL handle URLs. There is no special data type to handle them. In Django, however, there is. This type of higher definition capability gives you more control over your data types.

Creating a Model: First Steps — Configure the Database Settings

Because you used sqlite3 for the examples in Chapter 14, it only makes sense to use it here as well. Fortunately, because you are using Python 2.6 for this chapter, there are no additional components to install.

You will recall from the discussion on templates that you needed to change some settings in a file — appropriately named__settings.py__. For databases, you will need to use this file as well. If you closed the folder, never fear; you can find it by navigating to your newsite directory.

Open the file with Notepad or IDLE, and scan through the file until you see some code near the top, similar to the following:

DATABASE_ENGINE = ''           # 'postgresql_psycopg2', 'postgresql',
'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = ''             # Or path to database file if using sqlite3.
DATABASE_USER = ''             # Not used with sqlite3.
DATABASE_PASSWORD = ''         # Not used with sqlite3.
DATABASE_HOST = ''             # Set to empty string for localhost. Not used
with sqlite3.
DATABASE_PORT = ''             # Set to empty string for default. Not used
with sqlite3.

This is the portion of the __settings.py__ file where you configure your database. If you look at the comments for each option, you will notice that most of them require you to do nothing if you are using sqlite3 — yet another reason why it is a good idea to use it.

Still, although you only have to use two of these options, it is useful to understand what the rest do, in the event that you need to use a separate database program.

First in the list is Database Engine. This setting is where you tell Django which database engine you will be using. You can choose from four options, and each has a separate engine you will need to install if you want to use them with Django (again, if you are using SQLite3, you do not need to worry about downloading an engine). The four options are PostgreSQL (version 1.x and 2.x), MySQL, SQLite3, and Oracle. Whichever database you choose to use, you must place its name within the single quotes, like so:

DATABASE_ENGINE = 'sqlite3'

The preceding code tells Django to use SQLite3 as its database engine. If you wanted to use MySQL, you would change 'sqlite3' to 'mysql' If you wanted to use PostgreSQL version 1.x, you would replace it with 'postgresql' and so forth (note that version 2.x of PostgreSQL would use 'postgresql_psycopg2').

The next option is Database Name, which does exactly what might you might expect it to do — it allows you to specify to Django the name of the database you are going to be using. Because you are using SQLite3, you have to include a path to the database file you are using, such as the one shown here:

DATABASE_NAME = 'C:/Python26/Lib/site-packages/django/bin/newsite/sample_
database.db'

If you are not using SQLite3, you simply enter the name of the database file you want to use, and not the path:

DATABASE_NAME = 'sample_database'

Next up is the setting DATABASE_USER. This tells Django which user to connect to the database as. This is important because different database users can have different privileges. For SQLite3 users, this field is left blank. For any other systems, use something along these lines:

DATABASE_USER = 'chew_bacca'

And of course if you are signing in with a user name, you will likely have a password, so your next setting is DATABASE_PASSWORD. If you are using SQLite3, this is left blank. Likewise, if you do not use a password, it is also left blank. Otherwise, use the following convention:

DATABASE_PASSWORD = 'chewie'

Your last setting is DATABASE_HOST, which tells Django the host that it should use to connect to your database. As with most of the examples, if you are using SQLite3, this setting will be left blank. Likewise, if you are hosting the database on your own computer, you can leave this blank. Otherwise, enter the host name you are using.

That is all there is to configuring your database. If you want to make sure that it works, open up the Interactive Interpreter (as mentioned in the previous sections) by running manage.py shell. Then type in the following code:

>>>from django.db import connection
>>>cursor=connection.cursor()

If nothing happens when you type this, don't worry — your file is configured properly. If you get an error message, however, that means that something is not set properly in your file. Just read the error message you receive and go back through your file to ensure everything is set properly.

Creating a Model: Creating an Application

Applications — or Django Apps — are a Python package that consists of models, views, and a variety of other code. They differ from Django projects, in that Django projects consist of one or more applications and the settings for those applications.

Another difference between an application and a project is that you do not always need to create an application. In fact, the only instance where you really need to create an application (that is, where it is a requirement) is when you are using models or database-driven sites.

Now that you understand what an application is, how it differs from a project, and when it is a requirement, you can create your first one. The code is pretty simple. Just type the following into your command prompt (making sure you are in the newsite directory):

manage.py startapp employees

If nothing happens, you are in luck — you created an application. If you get an error it is likely because you are not in the appropriate directory or there was a typo. To see the results of what you just created, open up your newsite folder and take a gander. You should see a new directory called employees.

Click inside of that directory and you will see four files: __init.py__, __models.py__, __tests.py__, and __views.py__.

Conveniently, Django creates a blank model and view file for you — thoughtful, right? These are the files that you will be working with for the upcoming example.

For starters, open up the __models.py__ file and modify it so it looks like the following code:

from django.db import models

class Employer(models.Model):
    name = models.CharField(max_length=50)
    website = models.URLField()
    industry =models.CharField(max_length=50)

class Employee(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    address = models.CharField(max_length=50)
    hire_date = models.DateField()
    email = models.EmailField()

You start off this code by importing models from django.db. You then create your first class, Employer, which is a subclass of the models class. Next, you begin creating the fields that will be contained within the Employer class and defining their respective data type. It is important to know from here that the Employer class is now acting as the equivalent of a table in a database.

The first field in the Employer class is name, which you define as a CharField. The max_length=50 portion is where you set the parameter, which basically tells Django that the field contains characters, and no more than 50 of them.

You continue creating your second class, Employee, which will hold information about — you guessed it — the employees. Once all of the fields are done, you are finished creating your model.

Working with Models: Installation

Earlier, you created a model, which, as the name implies, is literally a model of what your data is going to look like and what type of data it will hold. Up to this point you haven't actually created the tables yet. To do that, you must install them.

To do this, you have to go back once in your newsite directory and open up the __settings.py__ file again. Scroll down until you see the section for Installed_Apps. You will notice that four files are already listed in here. Leave those alone for now, because they are default files. Simply modify the section so it looks like this:

INSTALLED_APPS = (
        'newsite.employees',
)

Next, modify the Middle_Ware Classes section by deleting the classes that are in there by default (the Installed Apps that you deleted rely on these and will cause errors when you try to create your database):

MIDDLEWARE_CLASSES = (

)

Now save the file and run the following command in your Interactive Interpreter:

manage.py validate

As is probably obvious from the command, this code validates your model and ensures that everything is defined properly. If you get a message saying 0 errors found, all is right in the world. If not, something was not defined properly in your model.

Now you are going to have Django create your tables by executing some SQL code for you. Type in the following:

manage.py syncdb employees

This code creates the tables in your database (assuming that they do not yet exist). You will see the following when you execute the command:

Creating table employees_employer
Creating table employees_employee

This means that it created the tables employer and employee in the employees.db. And that is all there is to installing your model!

Summary

You've really only touched the surface of what Django is capable of in this chapter. Alongside having the ability to create powerful and interactive websites in a snap, Django's true power lies in its database-driven capabilities. Though this chapter was not a comprehensive study (it would require a book about the same size as this one to accomplish that), it should be more than enough to get you started down the right path.

You started off learning Django's background and history, which is important to understand because it gives you some key insights as to why you may want to use Django, and what some of its strengths — and weaknesses — are. You also got an overview of frameworks in general, and took a rudimentary glance at the MVC and MTV architectures — the basic building blocks of a lot of frameworks.

After that, you dove into installing Django and worked on configuring your setup files. Then it was straight into creating URLConfs, views, templates, and — where you finally left off — models.

The key things to take away from this chapter are:

  • Django is a powerful tool in the online publication industry, but has potential for virtually every type of web application.

  • Django runs under the MVC architecture, or Model-Template-Controller, and is commonly said to truly be MTV or Model- Template-View.

  • Model is the actual data or content that is displayed in the page and is stored in a database, XML node, or other area.

  • View is the webpage, be it HTML, XHTML, or markup language.

  • Controller is the portion of code that collects the data from the model (database/xml) and passes it to the view (web page).

  • The __settings.py__ file is where you configure your Django settings. Here you can define which databases are being used, which applications, and much, much more.

  • Applications — or Django Apps — are a Python package that consists of models, views, and a variety of other code. They are different from Django projects, in that Django projects consist of one or more applications and the settings for those applications.

Exercises

  1. Configure the __settings.py file to work with each type of database that Django supports.

  2. Explain the MVC and MTV architectures and elaborate on the differences between the two.

  3. Create a template that shows the menu from a restaurant and have it display.

  4. Working with the same data fields you used in exercise 3, create a model that shows a menu from a restaurant and have Django create the database.

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

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