rick_grehan
Contributing Editor

Pillars of Python: Django Web framework

reviews
Aug 10, 20118 mins
Software DevelopmentWeb Development

Django combines excellent backward compatibility, good admin tools, and a focus on developer ease

The popular and well-regarded Django framework has been around since 2005. It is compatible with any 2.x Python from 2.4 onward, though 2.7 is recommended. The Django engineers are particularly sensitive to compatibility issues, so if a new release of Python adds a feature unavailable to earlier Django versions, engineers on the Django project will either modify code or release a library to make support in older Python versions transparent. 

Django ships with all the pieces you need to build a Web application, requiring minimal installation of separate components. The framework includes an ORM (object-relational mapping layer), a template library, a forms library, an URL dispatch mechanism, an administration interface, and other support libraries and useful applications. When you install Django, all that’s missing is an external RDBMS, and configuring a connection to a database is simple. 

The framework has out-of-the-box protection for most common Web attacks; XSS (cross-site scripting), CSRF (cross-site request forgeries), and SQL injection top the list. In fact, Django’s “by default” security features were given a tip of the hat by the Rails community when it introduced XSS protection in Ruby on Rails 3.

Django also provides a session management system, which handles the persisting of server-side session information and abstracting the passing of cookies as mechanisms for session support. It also installs an authentication library that supports the concepts of users and groups. Users can be assigned specific permissions (or given super user status), and the library provides functions for handling login/logout. To top it off, the administration utility (described below) that builds an application’s database also creates tables needed to support user authentication.

Django’s various elements are well integrated and nearly seamless. For example, you needn’t worry about converting data procured from the ORM into a format that Django’s form library can manipulate; that’s handled automatically. Small issues that make coding easier are attended to as well. For example, naming conventions across the different components are standardized, which makes navigating through APIs much easier than it otherwise would be.

Django: Model, template, view
Although Django does support MVC (model view controller) architecture, the correlation between the parts of the MVC acronym and elements in the framework are not straightforward. Dig through the documentation, and you’ll find references to the model layer and the view layer, but no references to the controller layer. In essence, the controller is spread throughout the Django framework. There is a “template layer” referred to in the Django documentation, but this is properly a part of the view layer. Nevertheless, Django engineers refer to the framework’s architecture as being “MTV” — model, template, view — as a way of separating the different concerns of the package.

Django includes a development Web server, based on the one provided in the Python language, for building and testing new applications. For deployment, Django’s engineers recommend one of the more robust Web servers — Apache, for example, though any Web server that supports either WSGI or FastCGI is suitable.

The included Web server has advantages at development time. For example, it will automatically reload any source file in your project that you’ve changed. In addition, you can configure an application to execute in debug mode, which provides extensive reporting when errors are raised. (In production mode, the error messages can be emailed to an administrator.)

The administration tool — django-admin.py — can be used to jump-start a new application and manage existing ones. When you create an application, the system also builds a special manage.py that serves as a management console for the specific application.

Once you’ve installed Django and are ready to build an application, you must first create a Django project like this:

django-admin.py startproject myProject

This builds a skeletal project directory, filled with required files. The website is currently an empty container; it has no database nor templates. So next, you create a database that the applications in your project will use, and to do that you must step outside of the Django tools, employing whatever management applications your database provides. That done, you record the database connection information in the settings.py file (which was created by django-admin).

You can now specify your application’s first project using manage.py:

manage.py startapp <appname>

This creates (among other things) a models.py file, the contents of which will define the application’s persistent objects. Classes defined in models.py are derived from a Django base class (models.Model) for persistent objects, and can employ methods that specify object attributes — such as the data type, including CharField(), DateTimeField(), and more, as well as relationships among persistent objects.

Finally, execute manage.py syncdb and the syncdb command will discover that the object classes you have just defined are not yet represented in your database, and it will generate and execute the necessary SQL to create them.

At this point, the model classes are available and fully functioning. You can open a Python session and explore the mechanics of your application’s persistent objects interactively. It’s important to note that Django’s ORM system requires that you explicitly save an object to the database, unlike some object database systems that track object changes implicitly and write the objects to the database whenever they become “dirty.”

Django: Templates and shortcuts
Django’s templating language was designed with ease-of-use in mind. Django engineers adopted the simplified syntax to enforce a clear separation between business logic and presentation code. Templating code is embedded directly into HTML in a format that includes two primary components: variables and tags.

Variables are named entities that are replaced by values at evaluation time. A variable’s value can be further modified when rendered by an attached filter. You might apply a filter to ensure a name field always begins with a capital letter, for example. Tags provide the means by which you can manipulate page structure rather than content. Using tags, you could define a looping construct for generating an HTML list from a variable defined as a collection.

Django templates support a kind of inheritance that lets you build “base” templates that can be inherited by “child” templates to create more complex templates that share common structures. Typically, a base template will define a “block” tag, which is a named region that can be filled in by any inheriting child template. You could use this architecture, for example, to create a base defining a header and footer, while leaving an interior content block empty for subsequent filling by a child template.

Django’s online documentation is excellent. The website provides a four-part tutorial, as well as a user guide that you can crawl through chapter by chapter as through an online book. In addition, the guide provides a view that organizes the content by architectural element, so you can quickly navigate to sections covering the view layer or model layer. Finally, the website also points to a series of how-to guides, all filled with plenty of example snippets.

Django’s developers are obviously familiar with common code constructs, and this pays off in numerous coding shortcuts for common tasks. For example, a frequent operation is to fetch an object from a database and render it on a page. But what happens if the object doesn’t exist? Typically, the developer will want to display a 404 page. Django provides a shortcut that allows you to fetch an object from the database, and if the object is not found, the fetch operation itself returns a ready-to-render 404 object. This saves the programmer the coding necessary to handle the catching of the exception and the generation of a “not found” object. It is such attention to details that makes Django a first-rate framework.

Read reviews of other Python Web frameworks: