Django
Web Development for
Perfectionists with Deadlines
Thursday 24 February 2011
Framework
» Models
» Define how a piece of data looks and works.
» Forget SQL, Django handles the database.
» Views
» A URL is mapped to a view.
» View pulls some objects based on a query.
» Creates a rendering context.
» Templates
» HTML code with some extra tags that insert some
content from the context.
Thursday 24 February 2011
A Django Project
» Separated into ‘apps’.
» Examples: /news/, /photos/, /events/
» Each app has its own models, views,
templates.
» A global URL mapper turns a URL into
a view located inside an app.
Thursday 24 February 2011
Speed Through It
Thursday 24 February 2011
Model
class Photo([Link]):
name = [Link](max_length=100)
file = [Link]()
owner = [Link](User)
pub_date = [Link]()
description = [Link]()
Thursday 24 February 2011
URL Map
url variable, will be passed as keyword argument to view function
(r‘photos/(?P<id>\d+)/$’, ‘photos.show_photo’),
regex describing url path
python package path to view function
Thursday 24 February 2011
View
def show_photo(request, id):
photo = [Link](id=id)
context = { ‘photo’: photo }
return render_to_response(‘[Link]’, context)
Thursday 24 February 2011
Template
{% extends ‘[Link]’ %}
{% block content %}
<h2>{{ [Link] }}</h2>
<em>Uploaded by: {{ [Link] }}<em></br>
<img src=”{{ [Link] }}” />
<p>
{{ [Link] }}
</p>
{% endblock %}
Thursday 24 February 2011
Installing Django
» Install Python! (duh)
» Install setuptools
» $ easy_install django
» > C:\Python2x\scripts\easy_install.exe django
Thursday 24 February 2011
Start a Project
» [Link] startproject mysite
Thursday 24 February 2011
Start an App
» cd mysite
» ./[Link] startapp photos
Thursday 24 February 2011
File Layout
__init__.py
[Link]
photos
photos/__init__.py
photos/[Link]
photos/[Link]
photos/[Link]
[Link]
[Link]
templates/[Link]
templates/[Link]
Thursday 24 February 2011
[Link]
» ./[Link] startapp [appname]
» ./[Link] runserver
» ./[Link] syncdb
Thursday 24 February 2011
[Link]
» Edit database config.
» Set up locale, timezones, translation.
» Set template directories.
» Load middleware.
» Load apps.
Thursday 24 February 2011
Built-in Apps
» Django comes with loads of built in
apps for various purposes.
» User authentication.
» Sessions.
» Admin site.
» Etc etc.
Thursday 24 February 2011
Designing URLs
[Link]
[Link]?pageid=144
[Link]
Thursday 24 February 2011
Designing URLs
0,2097,1-1-30-72-407-4752,[Link]
Thursday 24 February 2011
Designing URLs
photos/
photos/14/
photos/hamilton-at-night/
Thursday 24 February 2011
[Link]
from [Link] import *
from [Link] import admin
[Link]()
urlpatterns = patterns('',
(r'^admin/doc/', include('[Link]')),
(r'^admin/', include([Link])),
(r ^photos/(?P<id>\d+)/$ , photos.show_photo ),
(r ^$ , [Link] ),
)
Thursday 24 February 2011
About Models
» No SQL needed, Django handles it for whatever kind
of database you choose in [Link].
» SQLite for dev, deploy on MySQL, move to
Postgres later - no problem.
» Never risk SQL Injection. i.e. concatenating an SQL
query with some content a user submitted in a
form in order to construct a full query.
» Django lazily evaluates queries, won’t run a query
until you need to enumerate and print the result.
» Uses QuerySet objects for sorting, filtering,
querying.
Thursday 24 February 2011
About QuerySets
>>> [Link]()
>>> [Link](uploaded = today())
>>> [Link](name__startswith = ”Pants”)
>>> [Link](owner =
[Link](username=”theorie”))
Can also union and intersect querysets, drop into
SQL whenever you want.
Thursday 24 February 2011
Updating objects
>>> p = [Link](id=some_id)
>>> [Link] = “A new name”
>>> [Link]() # photo has been saved to the db
Thursday 24 February 2011
Admin Site
» Rapid development of new features.
» Knock out a model in 5 minutes.
» Get a writer on the admin site pushing
content.
» Finish view logic and templates.
» Feature deployed within the hour.
Thursday 24 February 2011
Thursday 24 February 2011
Thursday 24 February 2011
Thursday 24 February 2011
Batteries Included
» Generic Views
» Syndication
» Auth/Auth
» Comments
» i18n/l10n
» Caching framework
Thursday 24 February 2011
Generic Views
from [Link] import Photo
patterns = urlpatterns( ,
(r ^photos/$ ,
[Link].list_detail.object_list ,
{
queryset : [Link](),
paginate_by : 30
}
),
Thursday 24 February 2011
Syndication
from [Link] import Feed
from [Link] import Photo
class PhotoFeed(Feed):
title = My Photo Feed
link = /photos/
description = Photos from my site
def items(self):
return [Link]()[:20]
Thursday 24 February 2011
Syndication
» (r’^feeds/photos/$’, PhotoFeed()),
Thursday 24 February 2011
Auth/Auth
» Abstracted, use any method you want.
» Built-in Users, Groups, Permissions in
[Link]
» Authenticate using the local database.
» user = authenticate(username, password)
» [Link]() if user != None
» Attach any other auth system you can think of.
» Many available on the internet: LDAP, ActiveDirectory,
etc.
» Write your own, make a class that implements
authenticate(user, pass) and get_user(id), add it to
AUTHENTICATION_BACKENDS in [Link]
Thursday 24 February 2011
Auth/Auth
» Netsoc uses our own auth backend, based
on the LDAP method.
» Though unless you want to query LDAP
every time you need some user’s info, it’s
best to cache the user data in Django’s User
database locally as well.
» We also run through the LDAP groups that
the user belongs to and tag the local django
copy with things like is_staff and
is_superuser if the account is an admin or
member of webteam.
Thursday 24 February 2011
Comments
{% load comments %}
{% get_free_comment_list
for [Link] [Link]
as comments %}
{% for comment in comments %}
<h3>{{ comment.person_name }} said:</h3>
<p>{{ [Link] }}</p>
{% endfor %}
Thursday 24 February 2011
Comments
{% free_comment_form for [Link] [Link] %}
Thursday 24 February 2011
i18n/l10n
» Django’s core is translated into 63 languages.
» Easy to add localization to your projects.
» from [Link] import ugettext as _
» _(“This text will be translated”)
» {% trans “This text will be translated” %}
» [Link] makemessages -l fr
» [Link] compilemessages
» [Link][‘django_language’] = ‘fr’
Thursday 24 February 2011
Caching
» Various caching middleware is included.
» Filesystem
» Local memory
» Memcached
» Write your own caching backend.
» Add it to CACHES in [Link]
» Cache a whole view.
» Just cache part of a template, save caches based
on tags like username, language code, to keep
them relevant.
Thursday 24 February 2011
Learn More
» [Link]
» Thanks for coming.
» Slides are on [Link]
Thursday 24 February 2011