Web Development with Python using Django

Presentation URL

py-yyc.github.com/python-dojo-3

Github project URL

https://github.com/py-yyc/python-dojo-3

Gimme your github handles!

What is Django?

Django is a very popular Python web-framework that encourages rapid development and clean, pragmatic design.

As compared to Flask (from the last dojo) it:

- is pre-structured
- has more "magic" (not necessarily a good thing)
- has a steeper learning curve
- offers more "out-of-the-box" (not necessarily a good thing either)

Basic setup

The setup section does not assume any knowledge of Python development. And hence, it is boring!

But if you don’t know, don’t hesitate to check-out the slides.

Installation/Setup - part 1

I recommend you make and use a virtual environment:

$ cd /path/to/virtualenvs
$ virtualenv django-demo
$ cd django-demo
$ source bin/activate

Now install Django:

$ pip install Django

Installation/Setup - part 2

Now clone the project repo:

$ git clone git@github.com:py-yyc/python-dojo-3.git
$ cd python-dojo-3

Make your team branch:

$ git checkout -b team_awesome

Don’t push to the master branch!

$ git commit -m "Awesome feature added!"
$ git push origin team_awesome

Creating the project

Now that the boring part is over… oh wait!

$ django-admin.py startproject djangotodo
$ tree djangotodo/
djangotodo/
├── djangotodo
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
└── manage.py

WTH are all those files?

The structure of a Django project

The settings.py file obviously contains the various settings related to the project…

- The database connection settings
- The locations of static/media files
- and way too many other things...

The structure of a Django project

The manage.py file is a command-line utility suite containing lots of utilities for common administrative tasks like:

- syncing models with the real database
- creating apps etc.

More on some of these utilities later.

The structure of a Django project

# Remember the method decorators from Flask?
@app.route("/")
def hello():
    return "Hello World!"

The urls.py is a file containing these url-to-funtion mappings for the project

from django.conf.urls import patterns, include
urlpatterns = patterns('',
	url(r'^$', 'todo.views.hello'),
)

But where does my code go?

Introducing… Django applications

Django applications are modules of code that contain a single feature. Django projects contain many such applications.

$ ./manage.py startapp todolist
$ tree todolist/
todolist/
├── __init__.py
├── models.py
├── tests.py
└── views.py

Django application structure

Django comes bundled with its own ORM (Object Relation Mapping) system. You don’t have to use it but it is HIGHLY RECOMMENDED.

Models.py contains the object representations of your database tables.

from django.db import models
class Task(models.Model):
	description = models.TextField()
	# more fields like a done-flag, date etc. 
	# can be added to make this awesome

Django application structure

The actual web-requests are handled by methods called views.

from django.http import HttpResponse
def hello(request):
	return HttpResponse (
	    '''<html>
	        <body>
	            <h1>Hello, world!</h1>
	        </body>
	    </html>'''
	)

Django application structure

But nobody wants to write complicated HTML using a string in a function. For this, Django has its own templating language.

<html>
	<body><h1>Hello {{ username }}</h1></body>
</html>
from django.shortcuts import render
def hello(request):
	return render(request, 'todo/hello-template.html', {
	    'username': request.user.username
	})

Django application structure

Now that we’ve covered a Django app’s model, template and view components, I must tell you that this is the Django take on MVC. They call it MTV.

Now try Googling “Django MTV” and see how much Hollywood crap you have to sort through to get at the real stuff!

There is a spiel about this on the Django FAQ page if you’re interested.