Django Views and URLconfs – Your First Django page

This mini tutorial explains how to serve a simple web page through Django that display’s a traditional ‘Hello world’ message.

The examples on this page assume that you have completed the Django installation, and have started a new Django project in a directory named /mysite/.

Key concepts

In Django, the contents of the page are produced by view a function, which you place in a file you create, conventionally named The URL of the page itself is specified in a URLconf,, which you specify in

Sample view

To output a simple Hello world! message, add this to your new

from django.http import HttpResponsedef hello(request):     return HttpResponse("Hello world")


  • Import the HttpResponse class, from django/http/ (or, the django.http module)
  • Define a function called hello. This is our view function.
  • Return an HttpResponse object that’s been instantiated with the text Hello world.

In order for a Python function to be a Django view, it must do two things:

  1. Takes an HttpRequest as its first parameter.
  2. Return an instance of HttpResponse.

Each view function takes at least one parameter, called request by convention.

Sample URLconf

Default URLconf:

If we ignore the code that’s commented out of the file (the one that was created when you first created your Django testProject folder), we’re left simply with:

from django.conf.urls.defaults import *urlpatterns = patterns('',)


  • Import all objects from the django/conf/urls/defaults/ (the django.conf.urls.defaults module). This includes the proceeding function, patterns.
  • Calls the function patterns and save the result into a variable called urlpatterns.

Edit the URLconf:

from django.conf.urls.defaults import *from mysite.views import hellourlpatterns = patterns('',    ('^hello/$', hello),)


  • Import the hello view from the module.
  • Any request to the URL /hello/ should be handled by the hello view function.

Things to remember

  • mysite/ must be on your Python path.
  • If you want to load this page from Apache as instead of as from Django’s development server, make sure that the following is in Apache’s configuration file (httpd.conf):

    <Directory C:/mysite>
    Order deny,allow
    Allow from all </Directory>
  • The URLpattern ('^hello/$', hello), is a Python tuple in which the first element is a regular expression, and the second is the view function to use for that pattern.

Test your first Django page

Either run the command python runserver to view your /hello/ page in Django’s development server at, or view it with your Apache web server at .

The page you see from this example is static; the content doesn’t change from user input, nor does it involve any database. Move on to a simple example of a dynamic Django page—as well as to an introduction to dynamic URLs—in Chapter 3 of DjangoBook: Views and URLconfs.

Installing Python and Django on WampServer

Here’s a step by step guide to installing Python and Django on top of the WAMP stack. I’ve used Windows XP in this example, but there shouldn’t be much difference with Windows 2000, NT, 7, Vista, etc.

If you have any problems (or even if you don’t) don’t hesitate to leave your comments so others might benefit from your experience, good or bad.

1. Install Wampserver

The latest release of WAMP is WampServer 2.1a [24/12/10], and includes:

  • Apache 2.2.17
  • Php 5.3.3
  • Mysql 5.1.53 (version 64 bits)
  • Mysql 5.5.8 (version 32 bits)
  • PhpMyadmin
  • SQLBuddy 1.3.2

However, for this example I’m using the previous version of WampServer, 2.0-i [07/11/2009]. It’s unlikely this will cause you any problems. WampServer 2.0-i looks like this:

  • Apache 2.2.11
  • Php 5.3.0
  • Mysql 5.1.36
  • PhpMyadmin

Once WAMP is installed and running properly, give yourself a pat on the back on move on to step number 2.

2. Install Python

  1. Download a current production version of Python for Windows. At the time of this writing, Django supports 2.x versions only.
  2. Install your file (ex: python-2.7.1.msi) to your desired location. For this example, I’ll choose C:Python27
  3. Test Python’s interactive interpreterMake sure that your command window recognizes ‘python’ as a command to start the interpreter:
    1. Open your command window.
    2. Type the command python and hit enter.
    3. If things are working as they should, you should see something like:

      Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win32
      Type “help”, “copyright”, “credits” or “license” for more information.

    …and you can proceed to install Django.

    If instead you get an error such as:

    ‘python’ is not recognized as an internal or external command, operable program or batch file.

    then you’ll need to add Python’s installation directory path to your command window as an environmental variable. Here’s how it’s done in Windows XP:

    1. Go to the properties window of ‘My Computer’, and then to the ‘Advanced’ tab
    2. Click on ‘Environmental variables’ at the bottom of the ‘advanced’ tab.
    3. If there’s no PATH variable present on the left had side, click ‘new’ and add Path with a corresponding value on the right (in this case, C:Python27). You can choose to do this for either your Windows user account or system (all users). If a PATH variable is present, select it, click ‘edit’ and simply add the C:Python27 path as a variable directly after them, preceded by a semicolon as in fig 1.

      Add new environmental variable

      Fig. 1 – Add new environmental variable

    4. Click ‘ok’, and ‘ok’ again to close the ‘system properties’ window.
    5. Open a new command window, and type python and hit enter again. You should now see the message I mentioned earlier; something similar to:

      Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win32
      Type “help”, “copyright”, “credits” or “license” for more information.

      In the unlikely event that you still don’t see this message, it’s time to hit up Google and/or leave a comment at the end of this post.

3. Install the Python WSGI (Web Server Gateway Interface) adapter module for Apache

Mod_wsgi (pronounced as ‘wiz-gee’) is an Apache HTTP Server module that provides a WSGI compliant interface for hosting Python based web applications under Apache.

  1. Download mod_wsgi for your version of Apache and Python. For this example, I used since I’m running Apache 2.2 and Python 2.7.
  2. Rename the downloaded file to and move it to the modules/ folder of your Apache installation in WampServer.
  3. Add the following to your Apache configuration file (httpd.conf) for Apache to recognize python applications:LoadModule wsgi_module modules/
    and, to grant Apache rights to serve scripts from a directory we’ll use for our Django projects:
    <Directory C:/projects/testProject>
    Order deny,allow
    Allow from all

    Restart Apache
  4. Once you’ve got mod_wsgi installed and activated, add the following to your  httpd.conf file:

    WSGIScriptAlias / "c:/projects/testProject/django.wsgi"

    and then, create a file named django.wsgi. To it, add the following:
    import os, sys
    sys.path.append('c:/projects/') os.environ['DJANGO_SETTINGS_MODULE'] = 'testProject.settings'
    import django.core.handlers.wsgi
    application = django.core.handlers.wsgi.WSGIHandler()
    Place django.wsgi in c://wamp/www/projects/testProject.

4. Install Django

  1. Download Django, and unpack the tarball to any folder. Let’s use C:Documents and SettingsMattMy Documents. Once the tarball is unpacked, you’ll have a folder such as C:Documents and SettingsMattMy DocumentsDjango-1.3 which contain Django’s installation files. Copy this path from the address bar.
  2. Open a command window and change directory to Django’s installation files folder. In this case you would type cd C:Documents and SettingsMattMy DocumentsDjango-1.3.
  3. Verify that you see the contents of the folder with the dir command.
  4. Run the Django setup file by running
    python install
  5. Once the installation is complete, type python and hit enter to get the Python prompt, and then type import django. Hit enter.
  6. If nothing happens at this point, i.e., no errors appear, Django is successfully installed.
  7. Let’s test it.
    1. Create a folder for your various Django projects; say c:/projects/ for example. (Unlike with what you might be used to with PHP, your Python code and Django project files should be outside your Web server’s document root for added security).
    2. Open your command window and change directories to your c:/projects/ folder.
    3. Run the command startproject testProject

      to create a subfolder called testProject/ that will automatically contain 4 project files. If you get a command not found type error, it means you’ll need to add the path to as an environmental variable to window’s system path, similar to what you might have done when installing Python:

      1. Go to the properties window of ‘My Computer’, and then to the ‘Advanced’ tab.
      2. Click on ‘Environmental variables’ at the bottom of the ‘advanced’ tab.
      3. If there’s no PATH variable present on the left hand side, click ‘new’ and add Path with a corresponding value on the right (in this case, C:Python27Scripts). You can choose to do this for either your Windows user account or system (all users). If a PATH variable is present, select it, click ‘edit’ and simply add the C:Python27Scripts path as a variable directly after them, and preceded by a semicolon as in fig 2.
        Edit environmental variable

        Fig. 2 – Edit environmental variable

    4. When the command startproject testProject completes with no errors, you’ll have 4 project files. To verify that this this worked, cd to your c:projects/testProject/ directory and run the command python runserver . You’ll see the following output on the command line:
      Validating models...0 errors found.Django version 1.0, using settings 'mysite.settings'Development server is running at the server with CONTROL-C.

      This confirms that you’ve started the Django development server, a lightweight Web server written in Python.
      When Django’s development server is running, visit to see your first Django-powered page. This server is available to you should you prefer to use it over Apache. However, now that you’ve installed mod_wsgi, Django will run from Apache without having to start the development server at all.
      Visiting (no port 8000 specification) will confirm that django is now running on Apache.

      Since this guide focuses on using Django with WampServer, we’ll need to install the Python MySQL library next.

5. Install the Python MySQL library

The MySQL-Python package allows Python to interface with WampServer’s MySQL database.

  1. Download the most recent version of MySQL-Python for Windows.
  2. Run the installer.
  3. Send thanks to Ioannis Lalopoulos, his MySQL-Python module just saved you from spending a helluva lot of time trying to compile the MySQLdb on Windows.

Django’s MVC framework

Django is a Model–view–controller (MVC) framework, or software architecture. This type of architectural pattern isolates domain logic (the application logic for the user), user interface (input and presentation), and testing and maintenance of each (separation of concerns).

Standard MVC frameworks

Typically, an MVC framework looks like this:

  • Model: Database and business logic (domain logic).
  • View: The view manages the display of information, or look and feel.
  • Controller: The controller interprets the mouse and keyboard inputs from the user, and maps one to the other.

Django’s MVC framework

Django is more of a Model-Template-View framework due to its templating feature, where:

  • Model: Database and business logic (domain logic).
  • Template:  The separation of content from presentation.
  • View: In Django, the view describes which data is presented, not how you see it. In typical MVC frameworks, the view delegates to a template, which describes how the data is presented. According to Django’s FAQ page, …a “view” is the Python callback function for a particular URL, because that callback function describes which data is presented.

Django’s controller is the framework itself: the machinery that sends a request to the appropriate view, according to the Django URL configuration.

Beginning With Django, a Python Web Framework

So I’m not completely new to programming and scripting; I took a C++ course in university and some other introductory programming courses as well as a hardware course that focused on Assembly language.

I’ve coded several simple PHP scripts, performed basic MySQL queries, and I’ve modified code to suit my purposes in the past, but I’ve always hesitated to dig deeper into web development for 2 reasons. Ok, 3 reasons.

  1. Motivation: I’ve never had website functionality goals that spoke to me enough to push me past my next two reasons.
  2. Confusion: I’ve never been satisfied with just making code work. Unless I know I doing something the right way (within reasonable limits), I feel like I’m creating and reinforcing bad habits. That makes me feel like a goof and saps my motivation.
  3. Intimidation: There’s no question about it in my mind. Programming can seem hard. Fear causes stress, and personally, I find it almost impossible to absorb information when I’m stressed. Solution? Take it one step at a time and don’t expect too much out of yourself. Enjoy the process.

So there you have it. I’m moving past these reasons, excuses, no, reasons, and I’m moving forward. Why? The fascination of building websites with functionalities tailored to my specific goals is now too great to overlook.

My most recent motivation to enter the world of development is my discovery of the semantic Web. The ability to query large, semantically rich datasets using new languages such as SPARQL offers new opportunities for building unique information architectures with relative ease and freedom.

Django seems to be a good place to start.