Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (3 votes)
848 views

Django Tutorial

This document provides an overview of Django, an open-source web development framework. It discusses Django's model-view-template architecture, including models that define data, views that retrieve data and render templates, and templates that display HTML with dynamic content. It also covers installing Django, starting projects and apps, basic file structure, the admin site, generic views, and other built-in functionality like authentication, syndication, and caching.

Uploaded by

tcdnetsoc
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (3 votes)
848 views

Django Tutorial

This document provides an overview of Django, an open-source web development framework. It discusses Django's model-view-template architecture, including models that define data, views that retrieve data and render templates, and templates that display HTML with dynamic content. It also covers installing Django, starting projects and apps, basic file structure, the admin site, generic views, and other built-in functionality like authentication, syndication, and caching.

Uploaded by

tcdnetsoc
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

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(models.Model):
name = models.CharField(max_length=100)
file = models.ImageField()
owner = models.ForeignKey(User)
pub_date = models.DateTimeField()
description = models.TextField()

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 = Photo.objects.get(id=id)
context = { ‘photo’: photo }
return render_to_response(‘photo.html’, context)

Thursday 24 February 2011


Template
{% extends ‘base.html’ %}
{% block content %}
<h2>{{ photo.title }}</h2>
<em>Uploaded by: {{ photo.owner.username }}<em></br>
<img src=”{{ photo.url }}” />
<p>
{{ photo.description }}
</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

» django-admin.py startproject mysite

Thursday 24 February 2011


Start an App

» cd mysite
» ./manage.py startapp photos

Thursday 24 February 2011


File Layout
__init__.py
manage.py
photos
photos/__init__.py
photos/models.py
photos/tests.py
photos/views.py
settings.py
urls.py
templates/base.html
templates/photo.html
Thursday 24 February 2011
manage.py

» ./manage.py startapp [appname]


» ./manage.py runserver
» ./manage.py syncdb

Thursday 24 February 2011


settings.py

» 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
page.php

script.cgi?pageid=144

StoryPage.aspx

Thursday 24 February 2011


Designing URLs

0,2097,1-1-30-72-407-4752,00.html

Thursday 24 February 2011


Designing URLs

photos/

photos/14/

photos/hamilton-at-night/

Thursday 24 February 2011


urls.py
from django.conf.urls.defaults import *

from django.contrib import admin


admin.autodiscover()

urlpatterns = patterns('',
(r'^admin/doc/', include('django.contrib.admindocs.urls')),
(r'^admin/', include(admin.site.urls)),
(r ^photos/(?P<id>\d+)/$ , photos.show_photo ),
(r ^$ , photos.index ),
)

Thursday 24 February 2011


About Models
» No SQL needed, Django handles it for whatever kind
of database you choose in settings.py.

» 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
>>> Photo.objects.all()
>>> Photo.objects.filter(uploaded = today())
>>> Photo.objects.filter(name__startswith = ”Pants”)
>>> Photo.objects.filter(owner =
User.objects.get(username=”theorie”))

Can also union and intersect querysets, drop into


SQL whenever you want.

Thursday 24 February 2011


Updating objects

>>> p = Photos.objects.get(id=some_id)
>>> p.name = “A new name”
>>> p.save() # 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 mysite.models import Photo

patterns = urlpatterns( ,
(r ^photos/$ ,
django.views.generic.list_detail.object_list ,
{
queryset : Photo.objects.all(),
paginate_by : 30
}
),

Thursday 24 February 2011


Syndication
from django.contrib.syndication.feeds import Feed
from mysite.models import Photo

class PhotoFeed(Feed):
title = My Photo Feed
link = /photos/
description = Photos from my site

def items(self):
return Photo.objects.all()[: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


django.contrib.auth

» Authenticate using the local database.

» user = authenticate(username, password)

» user.login() 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 settings.py
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 photos.photos photo.id
as comments %}

{% for comment in comments %}


<h3>{{ comment.person_name }} said:</h3>
<p>{{ comment.comment }}</p>
{% endfor %}

Thursday 24 February 2011


Comments

{% free_comment_form for photos.photos photo.id %}

Thursday 24 February 2011


i18n/l10n
» Django’s core is translated into 63 languages.
» Easy to add localization to your projects.
» from django.utils.translation import ugettext as _

» _(“This text will be translated”)

» {% trans “This text will be translated” %}

» django-admin.py makemessages -l fr

» django-admin.py compilemessages

» request.session[‘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 settings.py
» 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

» djangoproject.com

» Thanks for coming.

» Slides are on netsoc.tcd.ie

Thursday 24 February 2011

You might also like