1. Overview

The aim of this book is to provide you with a practical guide to web development using Django. The book is designed primarily for students, providing a walkthrough of the steps involved in getting your first web applications up and running, as well as deploying them to a web server.

This book seeks to complement the official Django Tutorials and many of the other excellent tutorials available online. By putting everything together in one place, this book fills in many of the gaps in the official Django documentation providing an example-based design driven approach to learning the Django framework. Furthermore, this book provides an introduction to many of the aspects required to master web application development.

1.1. Why Work with this Book?

This book will save you time. On many occasions we’ve seen clever students get stuck, spending hours trying to fight with Django and other aspects of web development. More often than not, the problem was usually because a key piece of information was not provided, or something was not made clear. While the occasional blip might set you back 10-15 minutes, sometimes they can take hours to resolve. We’ve tried to remove as many of these hurdles as possible. This will mean you can get on with developing your application, and not have to sit there scratching your head.

This book will lower the learning curve. Web application frameworks can save you a lot of hassle and lot of time. Well, that is if you know how to use them in the first place! Often the learning curve is steep. This book tries to get you going - and going fast. By showing you how to put together a web application with all the bells and whistle from the onset, the book shortens the learning curve.

This book will improve your workflow. Using web application frameworks requires you to pick up and run with a particular design pattern - so you only have to fill in certain pieces in certain places. After working with many students, we heard lots of complaints about using web application frameworks - specifically about how they take control away from them (i.e. inversion of control). To help you, we’ve created a number of workflows to focus your development process so that you can regain that sense of control and build your web application in a disciplined manner.

This book is not designed to be read. Whatever you do, do not read this book! It is a hands-on guide to building web applications in Django. Reading is not doing. To increase the value you gain from this experience, go through and develop the application. When you code up the application, do not just cut and paste the code. Type it in, think about what it does, then read the explanations we have provided to describe what is going on. If you still do not understand, then check out the Django documentation, go to Stack Overflow or other helpful websites and fill in this gap in your knowledge. If you think it is worth mentioning, please get in touch with us so that we can improve the book - we already have a number of contributors and we will happily acknowledge your contribution!

1.2. What You will Learn

In this book, we will be taking an exampled-based approach (or inquiry-based learning). The book will show you how to design a web application called Rango (see the Design Brief in Section 1.4.1 below). Along the way, we’ll show you how to perform the following tasks.

  • Setup a development environment - including how to use the terminal, the Pip installer, how to work with Git, etc.
  • Setup a Django project and create a basic Django application.
  • Configure the Django project to serve static media and other media files.
  • Work with Django’s Model-View-Template design pattern.
  • Create database models and use the object relational mapping functionality provided by Django.
  • Create forms that can utilise your database models to create dynamically generated webpages.
  • Use the User Authentication services provided by Django.
  • Incorporate external services into the application.
  • Include Cascading Styling Sheets (CSS) and JavaScript within a web application.
  • Design and apply CSS to improve the look and feel the web application.
  • Work with cookies and sessions with Django.
  • Include more advanced functionality like AJAX into your application.
  • Deploy your application to a web server using PythonAnywhere.

At the end of each chapter, we have included a number of exercises designed to push you harder and to see if you can apply what you have learned. The later chapters of the book provide a number of open development exercises along with coded solutions and explanations. Finally, all the code is available from GitHub at https://github.com/leifos/tango_with_django.

To see a fully-functional version of the application, you can also visit the How to Tango with Django website at http://www.tangowithdjango.com/rango/.

1.3. Technologies and Services

Through the course of this book, we will used various technologies and external services, including:

We’ve selected these technologies and services as they are either fundamental to web development, and/or enable us to provide examples on how to integrate your web application with CSS toolkits (like Twitter Bootstrap), external services like (those provided by Microsoft Azure) and deploy your application quickly and easily (with PythonAnywhere).

1.4. Rango: Initial Design and Specification

As previously mentioned, the focus of this book will be to develop an application called Rango. As we develop this application, it will cover the core components that need to be developed when building any web application.

1.4.1. Design Brief

Your client would like you to create a website called Rango that lets users browse through user-defined categories to access various web pages. In Spanish, the word rango is used to mean “a league ranked by quality” or “a position in a social hierarchy” (see https://www.vocabulary.com/dictionary/es/rango).

  • For the main page of the site, they would like visitors to be able to see:
    • the 5 most viewed pages;
    • the five most rango’ed categories; and
    • some way for visitors to browse or search through categories.
  • When a user views a category page, they would like it to display:
    • the category name, the number of visits, the number of likes;
    • along with the list of associated pages in that category (showing the page’s title and linking to its url); and.
    • some search functionality (via Bing’s Search API) to find other pages that can be linked to this category.
  • For a particular category, the client would like the name of the category to be recorded, the number of times each category page has been visited, and how many users have clicked a “like” button (i.e. the page gets rango’ed, and voted up the social hierarchy).

  • Each category should be accessible via a readable URL - for example, /rango/books-about-django/.

  • Only registered users will be able to search and add pages to categories. And so, visitors to the site should be able to register for an account.

At first glance, the application to develop seems reasonably straightforward. In essence, it is just a list of categories which link to pages, right? However, there are a number of complexities and challenges that need to be addressed. First, let’s try and build up a better picture of what needs to be developed by laying down some high-level designs.

1.5. Exercises

Before going any further, think about these specifications and draw up the following design artefacts.

  • An N-Tier or System Architecture diagram.
  • Wireframes of the Main Page and the Category Page.
  • The URL Mappings.
  • An Entity-Relationship diagram to describe the data model that we’ll be implementing.

1.6. N-Tier Architecture

The high-level architecture for most web applications is a 3-Tier architecture. Rango will be a variant on this architecture as it interfaces with an external service.

Figure 1: Overview of the system architecture for Rango. Note the inclusion of an external Search Application Programming Interface (API).

Since we are building a web application with Django, we will use the following technologies for the following tiers.

  • The client will be a web browser (i.e Chrome, Firefox, Safari, etc.) which will render HTML/CSS pages.
  • The middleware will be a Django application, and will be dispatched through Django’s built-in development web server while we develop.
  • The database will be the Python-based SQLite3 Database engine.
  • The search API will be the Bing Search API.

For the most part, this book will focus on developing the middleware, though it should be quite evident from Figure 1 that we will have to interface with all the other components.

1.7. Wireframes

Wireframes are great way to provide clients with some idea of what the application should look like when complete. They save a lot of time, and can vary from hand drawn sketches to exact mockups depending on the tools that you have available. For Rango, we’d like to make the index page of the site look like the screen shot shown in Figure 2. Our category page is shown in Figure 3.


Figure 2: The index page with the categories bar on the left, also showing the top five pages and top five categories.


Figure 3: The category page showing the pages in the category (along with the number of views). Below, a search for Python has been conducted, with the results shown underneath.

1.8. Pages and URL Mappings

From the specification, we have already identified two pages that our application will present to the user at different points in time. To access each of these pages we will need to describe in some fashion the URL mappings. Think of a URL mapping as the text a user will have to enter into a browser’s address bar to reach the given page. The basic URL mappings for Rango are shown below.

  • /rango/ will point to the main (or index) page view.

  • /rango/about/ will point to an about page view.

  • /rango/category/<category_name>/ will point to the category page view for <category_name>, where the category might be:
    • games;
    • python recipes; or
    • code and compilers.
  • /rango/etc/, where etc could be replaced with a URL for any later function we wish to implement.

As we build our application, we will probably need to create other URL mappings. However, the ones listed above will get us started. We will also at some point have to transform category names in a valid URL string, as well as handle scenarios where the supplied category name does not exist.

As we progress through the book, we will flesh out how to construct these pages using the Django framework and use its Model-View-Template design pattern. However, now that we have a gist of the URL mappings and what the pages are going to look like, we need to define the data model that will house the data for our web application.

1.9. Entity-Relationship Diagram

Given the specification, it should be clear that we have at least two entities: a category and a page. It should also be clear that a category can house many pages. We can formulate the following ER Diagram to describe this simple data model.

Figure 4: The Entity Relationship Diagram of Rango’s two main entities.

Note that this specification is vague. One page may be in one or many categories. So we could model the relationship as a many-to-many. This approach however introduces a number of complexities, so we will make the simplifying assumption that one category contains many pages, but one page is assigned to one category. This does not preclude that the same page can be assigned to different categories - but the page would have to be entered twice, which may not be ideal.

It’s good practice to note down any working assumptions like this. You never know when they may come back to haunt you! By noting them down, this means you can communicate it with your development team and make sure that the assumption is sensible and that they are happy to proceed under such an assumption.

The resulting tables are shown below, where Str denotes a string or char field, Int denotes an integer field, URL denotes a URL field and FK denotes a Foreign Key.

Category Table   Page Table
Field Type Field Type
name Str   category FK
views Int   title Str
likes Int   url URL
      views Int

We will also have a User table - which we have not shown here, but shall introduce later in the book. In the following chapters will we see how to instantiate these data models in Django and how to use Django’s Object Relational Mapping to connect to the database.

1.10. Summary

These high level design and specifications will serve as a useful reference point when building our web application. While we will be focusing on using specific technologies, these steps are common to most database driven web sites. It’s a good idea to become familiar and comfortable with producing such specifications and designs.

If you already have Python 2.7.5 and Django 1.5.4 installed, you have a good working knowledge of the command line, configured your paths, then you can skip straight to the Django Basics chapter. Otherwise, get started with Chapter 2.

1.10.1. Working with The Official Django Tutorials

We suggest undertaking the Official Django Tutorials as part of the exercises associated with each of this book’s chapters. You can find a mapping between the tutorial exercises and book chapters below. The tutorial exercises will help reinforce your understanding of the Django framework, and also help you build up your skills.

Tango with Django Django Tutorial
Chapter 3 Part 1 - Models
Chapter 5 Part 2 - The Admin Interface
Chapter 6 Part 3 - URLs and Views
Chapter 7 Part 4 - Templates
Chapter 18 Part 5 - Testing
Chapter 11 Part 6 - CSS