Introduction to Django

../images/django/fisanotti.jpg

Author: Juan Pedro Fisanotti

Python is my favorite language, though I'm quite fond of Ruby and Lisp; Django is the web framework I like the most, Linux user (Ubuntu) from not too long ago, and free software enthusiast. Nowadays I mostly work with Python :)

../images/django/fisa.jpg

The original talk was titled "Mini-introduction to Django" but the written version wasn't so "mini".

../images/django/django1.png

So, ¿what's Django? In a few words: it is a web development framework. That is to say: a set of libraries and tools that will allow us to create websites. As you probably imagine, it's written in Python so it will also be Python (with all its benefits) the language that we use to create our websites.

Django is free software, so we have access to its source code to learn, understand, enhance it, etc. It also has a big and active community that helps keep it up to date, have bugs detected and squashed, an updated and detailed documentation, and some other advantages we'll later see (spoiler: a lot of useful applications already developed!).

What's more, it is good to know that Django has a well-defined philosophy, influenced by the environment it came from. The original Django creators worked building sites for news companies, where most of the times changes were needed within hours or days. Being a "perfectionist" group of developers their challenge was meet deadlines writing code the right way and not compromising to get it out the door faster.

Its from there that comes the saying that Django is "the web framework for perfectionists with deadlines". Django not only aids us in developing, it also actually helps us write good code.

Finally, it is a framework that tries to be flexible, not get in between the developer and what he wants to accomplish. That's why it is very simple replace the parts of Django we don't like for others we like more or are more useful.

Introductions out of the way (provided I didn't bore you to death and caused you to stop reading), let's get to know Django.

The first important thing to know is what Django proposes for our sites' structure:

../images/django/django2.png

In Django we will have Projects and Applications:

Something interesting to know is that Django promotes applications to be as independent as possible so that an application can be re-used in more than one project.

Django itself already brings a lot of useful applications for common web-development tasks like user authentication or content administration. And, having a community so huge (and humble as you can see), we can also find third-party applications to re-use and modify.

There are applications that will help during the development (logging, debugging, etc.), applications to add functionality to our website (tagging, registration, etc.) and pre-built applications to directly deploy in production (like blogs, CMS, etc.).

../images/django/django3.png

Now, what does an application look like?

For our applications Django proposes the Model-View-Controller (MVC) architecture. To those that have not heard about it beforehand, Django didn't invent MVC, it is a well-known architecture that proposes a 3-fold division of our applications:

Models will be classes that represent things that we want to store in the database. Example classes: Client, News, etc.

Views will be regular Python functions that will return the content that needs to be delivered to the user (webpage, image, etc). For example: the view "main_page".

And for controllers, we just need to define what function (view) is to be called for each URL. For example: "when the user asks for the URL http://misitio.com/start/ we run the view "main_page".

Django will take care of most of the controllers and provides us with tools to ease the development of models and views.

Lets take a look...

The Django package includes:

../images/django/django4.png

The first tool Django provides is an "Object Relational Mapper" (ORM). The ORM will allow us to interact with the database so it will be one of the two things that we will commonly use the most (so pay attention, this is like something that will be in the final for sure).

Like we are using object-oriented programming, we are going to define and use classes. Like most commonly used databases are relational databases, Django will take care of translating our operations on objects into SQL statements that will run on the databases' tables.

For example: we define our class User with several properties (name, address, email, etc.). We can then do things like create instances of User, store values in its properties and tell it: "hey, you, save yourself!", Django will automagically create the appropriate update or insert SQL statement and run it in the database.

The code for this example could look like this:

new_user = User()
new_user.name = 'Fisa'
new_user.email = 'fisadev@gmail.com'
new_user.address = 'somewhere in Argentina'
new_user.save()

Just like this, the ORM allows also us to read from the database, filter, run complex queries, etc.

For example, if we want to get all users that are 20 years old, it could be dome through some code like this:

past_teens = User.objects.filter(age = 20)

[while we are at it: Django's built-in authentication application already includes a User class that we can take advantage of :)]

../images/django/django5.png

We can now write code that reads from and stores stuff into the database, but that is not of much use to the user. We have to show him something. The second toll we're going to use is the templates system.

What's that? It is what will let us "inject" our data into HTML (or XML, or whatever) templates that we define.

That is to say that we'll build the HTML for the user to see in their browser but we'll say within the file things like "here goes the name of the current user".

The template language also provides some basic logic structures that we can use like loops, conditionals and even some kind of template inheritance.

../images/django/django6.png

There are also a number of extra tools that we will use intensely while developing with Django. It is always a good idea to get to know them so that we don't re-invent the wheel every time; they are also tools that have been thoroughly tested and polished.

If something smells popular, then it's probable that Django already has a tool to help with it. If there isn't one, it's very likely that someone developed it as an application. And if there is no such application, awesome! Now you found something you can contribute back :)

../images/django/django7.png

The tools we've seen so far are mostly things we will use only while we are developing. Things we will use within our code. But Django also comes with tools to help us with tasks beyond coding.

The development server will allow us to execute our website from the development environment itself, without the need to configure a web server for it or do complicated deployments for every change we make.

Django's console gives us the chance to run code in an Python interactive console, but just as if it was our site running in the server. We can use it, for example, to interact with the database with our models.

And there is the debug mode, that shows us a lot of information about the errors in our website's code execution. Having debug activated, when an error arises we will be able to see the code that generated it, the variables that were in memory at the time and their values, GET and POST parameters received, the site's configuration, Python's exception stack trace, etc. Those that have done previous web development know what that is worth as it is not normally available.

../images/django/django8.png

And to top off this list of tools and utilities, there is Django's Admin.

Django Admin is a builtin application that will save us a lot of work. I know it sounds exaggerated and fanatical, but my statement is quite realistic.

As you remember, we can define Models in our applications. Those are classes that represent the things that we store in the database (classes for User, News, Comment, etc.).

In the models we already defined everything needed to be able to operate with those entities in the database, create new ones, search, store, update, etc. So, what other thing is needed to get an application that provides functionality to administer the database's content? Logically, screens (pages).

Well, Django's Admin is exactly that. We simply tell it something like "hey, admin! Look, here I told that I had customers in the database, can you give me a customer's CRUD?". And the Admin will do just that. It's that simple (if you don't believe me, check the code of Django's tutorial).

[CRUD is an application that allows you to Create, Read, Update and Delete]

We can even customize the way those forms are shown so that we can add filters on fields of our choice, decide what columns to show in lists, how to show fields when editing, etc.

This application is of great use to us developers during the creation of the site to add content and get previews. It is also useful in production for the site's administrators or moderators. But it can also be of use to the end user, depending on the case.

Every time I see the admin, I regret the hours I devoted to developing CRUDs that are not a fraction as configurable as Django's :)

../images/django/screenshot_admin.png

Making it all work

Well, we have now gone through a few interesting things Django includes. The question now is: how do we put all these things together?

../images/django/django9.png

It is easier than it looks:

1. The user asks for a URL ("I want to get http://news.com/crimes really fast!")

2. Django realizes that to serve that URL needs to call a function (a view from now on). As you imagine, it does call it.

3. In our view (the function "cops" for example), we get the news from our database that are categorized as related to cops.

4. Finally, our view will tell Django to return to the user a specific template (in this case, the HTML of the cops page) but using the data we provide within the template.

So far we have a general idea of how it works and how to work with Django, but it can be understood a lot better if we see it with code. It is for that reason that I recommend the official Django tutorial that you can find at http://docs.djangoproject.com/en/dev/intro/tutorial01/

In the tutorial, you can see how to build a simple application from scratch. With what you read in this article it will surely be even easier to understand what you will be doing there.

And if it is not easier, you have my mail to complain :)

Help PET: Donate

blog comments powered by Disqus

Last Change: Sat Jul 9 15:00:35 2011.  -  This magazine is under a Creative Commons license