A Crash Course in Django

    Akash Mehta
    Akash Mehta

    Are you after a web framework that drastically cuts the time it takes to build data-driven web apps? If so, the Python-based Django might be worth investigating. With a unique architecture enabling extensive code reuse and an automatic admin system, Django is the state of the art for independent web developers, as well as being a strong tool for large scale web projects. In this article, I’ll show you how the basics of setting up your own Django-powered web site.

    Introducing Django

    Django is a fully-fledged, high-level web application framework that enables web developers to get robust applications up and running in record time. It’s powered by Python, which you might be unfamiliar with, but is easy to pick up. If you need a quick crash course in Python, I recommend Learn Python in 10 minutes, though A Quick, Painless Tutorial on the Python Language also offers a lot of depth.

    Django’s key feature for web developers is the concept of a single web site being powered by multiple, self-contained, function-based applications. These applications might provide a blog, a user login system, or even a TinyURL-style redirection service. Your web site consists of a set of applications, and when constructing it, you simply pick existing applications—or build your own—that provide the functionality you require.

    Another killer feature is the automatic admin system. When you build models in Django, you’re gifted with a free admin system to add, delete, and update them, managing the underlying database automatically. The admin system will provide a rich interface for end users to update the data in the database. The automatic admin system is a complete end-to-end solution as a data interface, and is ready for production use out of the box; it’s also extremely customizable.

    Before You Begin

    Before exploring this tutorial, you should have basic web development experience with database back ends, and preferably a basic Python background. Experience building PHP applications with some major framework is sufficient. Django takes advantage of sophisticated approaches to web applications and does require a solid grasp of web development concepts.

    You’ll need Django installed for this tutorial. Run through the installation documentation if you’ve yet to set this up, clicking on Install an official release. This article was written using 1.2 alpha; 1.1 is generally available and this tutorial should work with any 1.x release.

    When installing, make sure the django-admin.py tool is on your system path. This should happen automatically, but to check, open up your system’s terminal or command line console and run django-admin.py; if the output reads Type 'django-admin.py help' for usage (or something similar), you’re ready to go.

    To explore the Django framework, we’re going to create our own blog application (though there are plenty available) and use it to power a simple blog site. We’ll also be using the built-in admin, comments, and authentication applications. Make sure you’re comfortable with the command line, as we’ll be working with it frequently.

    You can download a copy of the finished application here, but we’ll be covering all the code required, so you’d be best to simply follow along and create the files as you go.

    Setting up the Admin Site

    Start by choosing a folder to store your Django projects—I use ~/Development/Django/—and switch to this folder on the command line. We need to start a new Django project for our web site, so run django-admin.py startproject spblog when you’re ready. Then switch to the newly created spblog folder and have a look at the files the django-admin.py utility created (Windows users: use dir instead of ls). This is what it all looks like in the terminal:

    $ cd ~/Development/Django$ django-admin.py startproject spblog$ cd spblog$ ls__init__.py  manage.py  settings.py  urls.py

    The django-admin.py script has created four files, but we only really need to worry about two: settings.py and urls.py.

    Your first Django app is now ready to go! Let’s start up a test server and take it for a spin:

    $ python manage.py runserverValidating models...0 errors foundDjango version 1.2 pre-alpha SVN-11600, using settings 'spblog.settings'Development server is running at the server with CONTROL-C.

    The manage.py script provides access to a number of helpful tools in the context of this particular Django project. One of these tools is a built-in web server (for development purposes only!), which is now serving up your web application at Load that URL in your web browser and you’ll see the following page.

    Figure 1. It worked!

    It worked!

    As the welcome page suggests, we still need an app to provide content to look at. Let’s start with the built-in administration site.

    To use the admin site, we first need to configure the database. We’ll use the file-based SQLite database, and install the admin application. First open settings.py and change the following settings:

    DATABASE_ENGINE = 'sqlite3'DATABASE_NAME = 'dev.db'

    We also need to add django.contrib.admin to the end of the INSTALLED_APPS setting: it should look like this:

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

    Now head back to your command line. We’re going to create the database using the manage.py syncdb command, which will also prompt us to create an administrator user account. Here’s what your command history should look like:

    $ python manage.py syncdbCreating table auth_permissionCreating table auth_groupCreating table auth_userCreating table auth_messageCreating table django_content_typeCreating table django_sessionCreating table django_siteCreating table django_admin_logYou just installed Django's auth system, which means you don't have any superusers defined.Would you like to create one now? (yes/no): yesUsername (Leave blank to use '…'): E-mail address: …Password: Password (again): Superuser created successfully.Installing index for auth.Permission modelInstalling index for auth.Message modelInstalling index for admin.LogEntry model

    Create an account with a username and password of your choice during the process—you’ll use this to log in to the admin site in a moment.

    There’s one more task we need to complete before we can use the admin site: configure the URLs. Django has a unique approach to URL routing, where URLs do not automatically map to specific request handling code (or controller methods/actions, if you’ve used another MVC framework). Instead, we use regular expressions to map URLs to views. For more details on URLs in Django, see the URL Dispatcher section in the documentation.

    Open urls.py and uncomment these lines related to the admin system (Python single-line comments begin with a #):

    from django.contrib import adminadmin.autodiscover()⋮(r'^admin/', include(admin.site.urls)), 

    Now, all URLs beginning with admin/ will be delegated to the admin system. In addition, we call the autodiscover method: this will make the admin system inspect the database to discover what database tables it will be managing. We put this command into urls.py, because it will be run once every time the server is started.

    Save urls.py and head back to your command line; the development server should have restarted automatically (if not, kill it with CtrlC and run it again).

    Now if we refresh our browser at http://localhost:8000/, we see a different page:

    Figure 2. Page not found

    Page not found

    This is a special 404 page for development purposes only—once you switch DEBUG from True to False in your settings, it will no longer appear. However, now that you have some URLs configured, Django no longer displays the welcome page, and instead offers a list of valid URLs (assuming the one you’re attempting to access is invalid). As our admin/ URL seems to be okay, let’s head to http://localhost:8000/admin/ to check out our admin site.

    Log in to the admin site using the username and password you configured while running the syncdb command; you should see the admin home page:

    Figure 3. Django administration

    Django administration

    Your admin site is ready to go! Take some time to explore, create some users, and experiment with the tools available.