SlideShare a Scribd company logo
The web framework for perfectionists with deadlines



James Casey
2nd October 2009
What’s Django?
“Django is a high-level Python Web framework that
encourages rapid development and clean, pragmatic
design.”



from http://djangoproject.org/
Whence Django ?
‣ Internal project of newspaper in 2003
  ‣ Lawrence Journal-World
‣ Should help journalist meet faster deadlines
‣ Should not stand in the way of journalists
‣ Named after the famous guitarist Django
  Reinhardt
Django in the news

     ‣ http://mps-expenses.guardian.co.uk/
     ‣ MP expense scandal
        ‣ crowdsourcing the review of 500K
          documents
        ‣ 7 days from proof-of-concept to launch


http://simonwillison.net/2009/talks/europython-crowdsourcing/
Django won a pulitzer

     ‣ http://polifact.com/
        ‣ Fact checking in 2008 US presidental
          election
     ‣ Lead developer was former journalist
        ‣ It was his ïŹrst django application


http://www.mattwaite.com/posts/2007/aug/22/announcing-politifact/
Overview
Principles
‣ DRY (Don’t Repeat Yourself)
‣ Write less code
‣ Make CRUD easy
‣ DB neutral
 ‣ Oracle, MySQL, PostgreSQL, SQLlite
‣ Deployment platform neutral
 ‣ mod_python, WSGI, ...
It’s (just) python
Features
‣ Object-relational mapping (ORM)
‣ Automatic admin interface
‣ Elegant URL design
‣ Template system
‣ Caching
‣ i18n
Architecture

             Browser


  Template             URL


              Views


             Models


         Database
Model-Template-View

‣ Models : What things are

‣ Views : How things are processed

‣ Templates : How things are presented
Models
from django.db import models

class Author(models.Model):
   name = models.CharField(max_length=100)
   age = models.IntegerField()
   friends = models.ManyToManyField('self', blank=True)

class Publisher(models.Model):
   name = models.CharField(max_length=300)
   num_awards = models.IntegerField()

class Book(models.Model):
   isbn = models.CharField(max_length=9)
   name = models.CharField(max_length=300)
   pages = models.IntegerField()
   price = models.DecimalField(max_digits=10, decimal_places=2)
   rating = models.FloatField()
   authors = models.ManyToManyField(Author)
   publisher = models.ForeignKey(Publisher)
   pubdate = models.DateField()
Represents the
          database objects
BEGIN;
CREATE TABLE `tutorial_author` (
    `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
    `name` varchar(100) NOT NULL,
    `age` integer NOT NULL
);
CREATE TABLE `tutorial_publisher` (
    `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
    `name` varchar(300) NOT NULL,
    `num_awards` integer NOT NULL
);

...
...

COMMIT;
ORM
books = Book.objects.all()

books_this_year = Book.objects.filter(pubdate__gt = jan_1st)

apress_books = Book.objects.filter(publisher__name = ‘Apress’)




     ‣ Never write SQL again
       ‣ Unless you really need to
Views
‣ Where all the magic happens
‣ Normally :
 ‣ Process model instances
 ‣ Render HTML
‣ Keep your logic in the model !
import datetime

def view_latest_books(request):
    # Last 5 days
    date = datetime.datetime.now() -
                       datetime.timedelta(5)
    books = Book.objects.filter(pubdate__gte =
                                date).order_by('-pubdate')

   return render_to_response('tutorial/show_books.html',
                             {'books': books})
Templates

‣ Separate design from code

‣ Separate designers from code

‣ Separate design from developers
“base.html”



<html>
  <head>
    <title>{% block title %}{% endblock %}</title>
  </head>
  <body>
    {% block content %}{% endblock %}
  </body>
</html>
“index.html”

{% extends "tutorial/base.html" %}
{% block title %}Homepage{% endblock %}
{% block content %}
  {% for book in books %}
    <h4>{{ book.name }}</h4>
    <p>Publisher: {{ book.publisher }}</p>
    <p>Date of Publication: {{ book.pubdate|date }}</p>
    <p>Price ${{ book.price }}</p>
    <p>Author : {% for a in book.authors.all %}{{ a.name }}{% if not
forloop.last %}, {% endif %}{% endfor %}</p>
  {% endfor %}
{% endblock %}
Security advantages
‣ No raw SQL from the users
 ‣ We deal with models and queries
‣ Automatic HTML escaping
 ‣ No XSS attacks
‣ CSRF protection
 ‣ No replay of forms by other code
This cannot happen !
URLs

urlpatterns = patterns('apps.tutorial.views',
    (r'^$', 'index'),

    (r’^book/<?P<id>d+)/$’, ‘show_book’),
    (r'^latest/(?P<num_days>d+)/$', 'view_latest_books'),
    (r'^create/$', 'create'),
)




       ‣ URLs map to views (via regular expressions)
http://example.com/tutorial/

http://example/com/tutorial/books/

http://example.com/tutorial/create/

http://example.com/tutorial/latest/5/
Views are just python
          functions
import datetime

def view_latest_books(request, num_days):
    date = datetime.datetime.now() -
                       datetime.timedelta(int(num_days))
    books = Book.objects.filter(pubdate__gte =
                                date).order_by('-pubdate')

   return render_to_response('books/show_books.html',
                             {'books': books})
Aggregation
      ‣ When you need to summarise a collection
        of objects
         ‣ Leveraging the DB where possible

  > q = Book.objects.annotate(num_authors=Count('authors'))
  > [b.num_authors for b in q]
  [2, 3, 1]
  > Store.objects.aggregate(min_price=Min('books__price'),
                            max_price=Max('books__price'))
  {‘min_price’ : 2.99, ‘max_price’ : 29.99}



http://docs.djangoproject.com/en/dev/topics/db/aggregation/
Other features
‣ Forms
‣ Generic Views
 ‣ Makes CRUD simple
‣ User management
‣ i18n
My ïŹrst django project
Projects contain Applications
                       Project


                  my
                                  myapp
               other_app

                      reuseable
                         app


‣ Application : self-contained set of functions
‣ Project : collection of applications, installed
  into same database
  ‣ roughly project == a web application - has a
    settings ïŹle
Getting started
‣ Install Django 1.1
 > easy_install django

‣ Create a project
 > django-admin.py startproject new_django_project

   new_django_project/
       __init__.py
       manage.py
       settings.py
       urls.py
> ./manage.py startapp tutorial


 new_django_project/
     __init__.py
     manage.py
     settings.py
     tutorial/
         __init__.py
         models.py
         tests.py
         views.py
     urls.py
> ./manage.py runserver
Validating models...
0 errors found

Django version 1.1, using settings 'new_django_project.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
...


‣ Now you write your code ...
> ./manage.py syncdb
Creating table django_content_type
Creating table django_session
Creating table django_site
Creating table tutorial_author
Creating table tutorial_publisher
Creating table tutorial_book
Creating table tutorial_store
Installing index for tutorial.Book model
automatic admin interface


   http://localhost:8000/admin/tutorial/
manage.py
‣ syncdb : create SQL for your models
‣ shell : start up a python shell with your
  django project loaded
‣ test : run your unit tests
    ‣ you did write some, didn’t you ?
‣ inspectdb : reverse engineer models for
  existing DB
‣ loaddata / dumpdata : load/dump your
  ïŹxtures from a DB
Tools to make you
 more productive
   all just an easy_install away
distutils
‣ ‘standard’ python packaging
  ‣ ./setup.py sdist : source packages
  ‣ /.setup.py bdist : binary packages
‣ Nice to integrate with other tools
  ‣ pip, unittest, ...
‣ ./setup.py bdist_rpm : Can produce rpm
Virtualenv
‣ Run separate python environments
 ‣ With different sets of packages
 ‣ And even different interpreters
‣ Easily switch between then
 ‣ virtualenv_wrapper gives nice bash
   functions for it all

   http://pypi.python.org/pypi/virtualenv
ipython
‣ python with CLI hotness
 ‣ TAB autocomplete
 ‣ code coloring
 ‣ nicer pdb integration
 ‣ ...


         http://ipython.scipy.org/moin/
Introduction to Django
PIP
‣ Better installation manager
  ‣ ‘easy_install’ with dependency ordering
  ‣ Integrated with virtualenv
  ‣ Allow to ‘freeze’ a set of packages
    ‣ and re-install to the same level


       http://pypi.python.org/pypi/pip
django-debug-toolbar


  http://localhost:8000/tutorial/
django-command-extensions

 ‣ Extra manage.py commands
  ‣ shell_plus : a better python shell
  ‣ runserver_plus : a better debugging
    server (werkzeug)
  ‣ show_urls : dump the url map of your
    site
Werkzeug


http://localhost:8000/tutorial/latest/5
and of course, unittest
‣ Django supports :
 ‣ doctest : useful for simple model validation
 ‣ unittest : you did write some, didn’t you ?
 ‣ test client : acts a dummy web browser
   ‣ Test your views
 ‣ ïŹxture loading : have a set of complex test data
   ‣ generated from your production database
reusable apps
if it’s useful, it’s probably been done before...
south

‣ Schema migration
 ‣ Change models over time
 ‣ Write upgrade routines
   ‣ just python functions with access
     to .objects and .old_objects
A platform for rapidly developing (social) websites
code.google.com

‣ just search for django-<WHATEVER> :)
‣ It’s probably there...
  ‣ If it’s not there, write it and put it there
Future
beyond django 1.1
Multi-DB

‣ Allows your models to be in multiple DBs
 ‣ Different applications in different DBs
 ‣ ‘sharding’ of objects across DBs
 ‣ using slaves for read-only operations
Other
‣ Admin UI enhancements
 ‣ autocompletion
 ‣ better inline handling
‣ Non-relational database support
   ‣ CouchDB, MongoDB, tokyo Tyrant,
     Google Bigtable, SimpleDB
want more ?
‣ http://docs.djangoproject.com/
‣ Django community RSS feed
  ‣ http://www.djangoproject.com/community/
‣ Mailing lists
  ‣ django-dev to understand how the developers
    think
  ‣ django-users to ask for help
‣ DjangoCon presentations
  ‣ http://www.djangocon.org/
Books
django-users@cern.ch
Thank you
Credits
‣ XKCD for cartoons
‣ Amazon.com for book pictures
‣ Initial inspiration for slides and examples
  from Joaquim Rocha, Abe Estrada
  ‣   http://www.slideshare.net/j_rocha/django-intro

  ‣   http://www.slideshare.net/AbeEstrada/django-web-framework-presentation-822177


‣ http://www.djangoproject.com/

More Related Content

PDF
A Basic Django Introduction
Ganga Ram
 
ODP
Django for Beginners
Jason Davies
 
PPTX
Introduction to Django
Knoldus Inc.
 
PDF
Django Introduction & Tutorial
äč‹ćź‡ è¶™
 
PDF
Introduction to django framework
Knoldus Inc.
 
PDF
Web Development with Python and Django
Michael Pirnat
 
PPTX
PowerPoint basics
hope baido
 
PPSX
Modules and packages in python
TMARAGATHAM
 
A Basic Django Introduction
Ganga Ram
 
Django for Beginners
Jason Davies
 
Introduction to Django
Knoldus Inc.
 
Django Introduction & Tutorial
äč‹ćź‡ è¶™
 
Introduction to django framework
Knoldus Inc.
 
Web Development with Python and Django
Michael Pirnat
 
PowerPoint basics
hope baido
 
Modules and packages in python
TMARAGATHAM
 

What's hot (20)

PPTX
Django - Python MVC Framework
Bala Kumar
 
PPT
Introduction To Django
Jay Graves
 
PDF
Introduction to django
Ilian Iliev
 
PPTX
Web development with django - Basics Presentation
Shrinath Shenoy
 
PPTX
Django Girls Tutorial
Kishimi Ibrahim Ishaq
 
PPTX
Django
Sayeed Far Ooqui
 
PPTX
Django Architecture Introduction
Haiqi Chen
 
PPTX
Django Framework Overview forNon-Python Developers
Rosario Renga
 
PPT
Django, What is it, Why is it cool?
Tom Brander
 
PDF
Django Tutorial | Django Web Development With Python | Django Training and Ce...
Edureka!
 
PPTX
Flask – Python
Max Claus Nunes
 
PPTX
Python/Flask Presentation
Parag Mujumdar
 
PPTX
Object oriented programming in python
baabtra.com - No. 1 supplier of quality freshers
 
PPT
DJango
Sunil OS
 
PPTX
Angular modules in depth
Christoffer Noring
 
PDF
Python Django tutorial | Getting Started With Django | Web Development With D...
Edureka!
 
PPTX
Introduction to Django
Ahmed Salama
 
PPTX
django
Mohamed Essam
 
PPT
Jsp/Servlet
Sunil OS
 
Django - Python MVC Framework
Bala Kumar
 
Introduction To Django
Jay Graves
 
Introduction to django
Ilian Iliev
 
Web development with django - Basics Presentation
Shrinath Shenoy
 
Django Girls Tutorial
Kishimi Ibrahim Ishaq
 
Django Architecture Introduction
Haiqi Chen
 
Django Framework Overview forNon-Python Developers
Rosario Renga
 
Django, What is it, Why is it cool?
Tom Brander
 
Django Tutorial | Django Web Development With Python | Django Training and Ce...
Edureka!
 
Flask – Python
Max Claus Nunes
 
Python/Flask Presentation
Parag Mujumdar
 
Object oriented programming in python
baabtra.com - No. 1 supplier of quality freshers
 
DJango
Sunil OS
 
Angular modules in depth
Christoffer Noring
 
Python Django tutorial | Getting Started With Django | Web Development With D...
Edureka!
 
Introduction to Django
Ahmed Salama
 
django
Mohamed Essam
 
Jsp/Servlet
Sunil OS
 
Ad

Viewers also liked (8)

PPTX
Tango with django
Rajan Kumar Upadhyay
 
KEY
Django In The Real World
Jacob Kaplan-Moss
 
PPTX
Blog project
shara831
 
PPTX
Blog Project
Shawn Quait
 
KEY
Jumpstart Django
ryates
 
PDF
Two scoops of Django - Security Best Practices
Spin Lai
 
PDF
Django in the Real World
Jacob Kaplan-Moss
 
PDF
12 tips on Django Best Practices
David Arcos
 
Tango with django
Rajan Kumar Upadhyay
 
Django In The Real World
Jacob Kaplan-Moss
 
Blog project
shara831
 
Blog Project
Shawn Quait
 
Jumpstart Django
ryates
 
Two scoops of Django - Security Best Practices
Spin Lai
 
Django in the Real World
Jacob Kaplan-Moss
 
12 tips on Django Best Practices
David Arcos
 
Ad

Similar to Introduction to Django (20)

PDF
Introduction to Django
Joaquim Rocha
 
PPT
Mini Curso Django Ii Congresso Academico Ces
Leonardo Fernandes
 
PDF
How to Webpack your Django!
David Gibbons
 
PDF
Mini Curso de Django
Felipe Queiroz
 
PPTX
Django crush course
Mohammed El Rafie Tarabay
 
PDF
Turku loves-storybook-styleguidist-styled-components
James Stone
 
PDF
ŰšŰ±Ű±ŰłÛŒ Ú†Ű§Ű±Ú†ÙˆŰš ŰŹÙ†ÚŻÙˆ
railsbootcamp
 
PDF
Virtual Environment and Web development using Django
Sunil kumar Mohanty
 
KEY
Introduction to Palm's Mojo SDK
Brendan Lim
 
PDF
GDG Addis - An Introduction to Django and App Engine
Yared Ayalew
 
PPTX
React django
Heber Silva
 
PPTX
End-to-end testing with geb
JesĂșs L. DomĂ­nguez Muriel
 
PDF
Gae Meets Django
fool2nd
 
PDF
django
webuploader
 
PDF
Building Grails Plugins - Tips And Tricks
Mike Hugo
 
PDF
Build and deploy Python Django project
Xiaoqi Zhao
 
PDF
Google App Engine in 40 minutes (the absolute essentials)
Python Ireland
 
PPT
JBUG 11 - Django-The Web Framework For Perfectionists With Deadlines
Tikal Knowledge
 
PDF
EP2016 - Moving Away From Nodejs To A Pure Python Solution For Assets
Alessandro Molina
 
PPTX
Hands on django part 1
MicroPyramid .
 
Introduction to Django
Joaquim Rocha
 
Mini Curso Django Ii Congresso Academico Ces
Leonardo Fernandes
 
How to Webpack your Django!
David Gibbons
 
Mini Curso de Django
Felipe Queiroz
 
Django crush course
Mohammed El Rafie Tarabay
 
Turku loves-storybook-styleguidist-styled-components
James Stone
 
ŰšŰ±Ű±ŰłÛŒ Ú†Ű§Ű±Ú†ÙˆŰš ŰŹÙ†ÚŻÙˆ
railsbootcamp
 
Virtual Environment and Web development using Django
Sunil kumar Mohanty
 
Introduction to Palm's Mojo SDK
Brendan Lim
 
GDG Addis - An Introduction to Django and App Engine
Yared Ayalew
 
React django
Heber Silva
 
End-to-end testing with geb
JesĂșs L. DomĂ­nguez Muriel
 
Gae Meets Django
fool2nd
 
django
webuploader
 
Building Grails Plugins - Tips And Tricks
Mike Hugo
 
Build and deploy Python Django project
Xiaoqi Zhao
 
Google App Engine in 40 minutes (the absolute essentials)
Python Ireland
 
JBUG 11 - Django-The Web Framework For Perfectionists With Deadlines
Tikal Knowledge
 
EP2016 - Moving Away From Nodejs To A Pure Python Solution For Assets
Alessandro Molina
 
Hands on django part 1
MicroPyramid .
 

More from James Casey (9)

PDF
Habitat on AKS - Demo
James Casey
 
PPTX
Compliance at Velocity with Chef
James Casey
 
PPTX
Chef Analytics Webinar
James Casey
 
PDF
Chef Analytics (Chef NYC Meeting - July 2014)
James Casey
 
PPTX
Chef Actions: Delightful near real-time activity tracking!
James Casey
 
PDF
Chef - Configuration Management for the Cloud
James Casey
 
PPT
WLCG Grid Infrastructure Monitoring
James Casey
 
PPTX
1005 cern-active mq-v2
James Casey
 
KEY
Grid Information systems from an Operations Perspective
James Casey
 
Habitat on AKS - Demo
James Casey
 
Compliance at Velocity with Chef
James Casey
 
Chef Analytics Webinar
James Casey
 
Chef Analytics (Chef NYC Meeting - July 2014)
James Casey
 
Chef Actions: Delightful near real-time activity tracking!
James Casey
 
Chef - Configuration Management for the Cloud
James Casey
 
WLCG Grid Infrastructure Monitoring
James Casey
 
1005 cern-active mq-v2
James Casey
 
Grid Information systems from an Operations Perspective
James Casey
 

Recently uploaded (20)

PDF
DevOps & Developer Experience Summer BBQ
AUGNYC
 
PDF
Software Development Company | KodekX
KodekX
 
PPTX
Coupa-Overview _Assumptions presentation
annapureddyn
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PDF
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
PPTX
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
PDF
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
PDF
Orbitly Pitch DeckA Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
PDF
REPORT: Heating appliances market in Poland 2024
SPIUG
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
Software Development Methodologies in 2025
KodekX
 
PDF
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
PPTX
Comunidade Salesforce SĂŁo Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira JĂșnior
 
PDF
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
PPTX
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PDF
This slide provides an overview Technology
mineshkharadi333
 
PDF
Chapter 1 Introduction to CV and IP Lecture Note.pdf
Getnet Tigabie Askale -(GM)
 
PDF
Best ERP System for Manufacturing in India | Elite Mindz
Elite Mindz
 
PPTX
Stamford - Community User Group Leaders_ Agentblazer Status, AI Sustainabilit...
Amol Dixit
 
DevOps & Developer Experience Summer BBQ
AUGNYC
 
Software Development Company | KodekX
KodekX
 
Coupa-Overview _Assumptions presentation
annapureddyn
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
Orbitly Pitch DeckA Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
REPORT: Heating appliances market in Poland 2024
SPIUG
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Software Development Methodologies in 2025
KodekX
 
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
Comunidade Salesforce SĂŁo Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira JĂșnior
 
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
This slide provides an overview Technology
mineshkharadi333
 
Chapter 1 Introduction to CV and IP Lecture Note.pdf
Getnet Tigabie Askale -(GM)
 
Best ERP System for Manufacturing in India | Elite Mindz
Elite Mindz
 
Stamford - Community User Group Leaders_ Agentblazer Status, AI Sustainabilit...
Amol Dixit
 

Introduction to Django

  • 1. The web framework for perfectionists with deadlines James Casey 2nd October 2009
  • 2. What’s Django? “Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design.” from http://djangoproject.org/
  • 3. Whence Django ? ‣ Internal project of newspaper in 2003 ‣ Lawrence Journal-World ‣ Should help journalist meet faster deadlines ‣ Should not stand in the way of journalists ‣ Named after the famous guitarist Django Reinhardt
  • 4. Django in the news ‣ http://mps-expenses.guardian.co.uk/ ‣ MP expense scandal ‣ crowdsourcing the review of 500K documents ‣ 7 days from proof-of-concept to launch http://simonwillison.net/2009/talks/europython-crowdsourcing/
  • 5. Django won a pulitzer ‣ http://polifact.com/ ‣ Fact checking in 2008 US presidental election ‣ Lead developer was former journalist ‣ It was his ïŹrst django application http://www.mattwaite.com/posts/2007/aug/22/announcing-politifact/
  • 7. Principles ‣ DRY (Don’t Repeat Yourself) ‣ Write less code ‣ Make CRUD easy ‣ DB neutral ‣ Oracle, MySQL, PostgreSQL, SQLlite ‣ Deployment platform neutral ‣ mod_python, WSGI, ...
  • 9. Features ‣ Object-relational mapping (ORM) ‣ Automatic admin interface ‣ Elegant URL design ‣ Template system ‣ Caching ‣ i18n
  • 10. Architecture Browser Template URL Views Models Database
  • 11. Model-Template-View ‣ Models : What things are ‣ Views : How things are processed ‣ Templates : How things are presented
  • 12. Models from django.db import models class Author(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() friends = models.ManyToManyField('self', blank=True) class Publisher(models.Model): name = models.CharField(max_length=300) num_awards = models.IntegerField() class Book(models.Model): isbn = models.CharField(max_length=9) name = models.CharField(max_length=300) pages = models.IntegerField() price = models.DecimalField(max_digits=10, decimal_places=2) rating = models.FloatField() authors = models.ManyToManyField(Author) publisher = models.ForeignKey(Publisher) pubdate = models.DateField()
  • 13. Represents the database objects BEGIN; CREATE TABLE `tutorial_author` ( `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `name` varchar(100) NOT NULL, `age` integer NOT NULL ); CREATE TABLE `tutorial_publisher` ( `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `name` varchar(300) NOT NULL, `num_awards` integer NOT NULL ); ... ... COMMIT;
  • 14. ORM books = Book.objects.all() books_this_year = Book.objects.filter(pubdate__gt = jan_1st) apress_books = Book.objects.filter(publisher__name = ‘Apress’) ‣ Never write SQL again ‣ Unless you really need to
  • 15. Views ‣ Where all the magic happens ‣ Normally : ‣ Process model instances ‣ Render HTML ‣ Keep your logic in the model !
  • 16. import datetime def view_latest_books(request): # Last 5 days date = datetime.datetime.now() - datetime.timedelta(5) books = Book.objects.filter(pubdate__gte = date).order_by('-pubdate') return render_to_response('tutorial/show_books.html', {'books': books})
  • 17. Templates ‣ Separate design from code ‣ Separate designers from code ‣ Separate design from developers
  • 18. “base.html” <html> <head> <title>{% block title %}{% endblock %}</title> </head> <body> {% block content %}{% endblock %} </body> </html>
  • 19. “index.html” {% extends "tutorial/base.html" %} {% block title %}Homepage{% endblock %} {% block content %} {% for book in books %} <h4>{{ book.name }}</h4> <p>Publisher: {{ book.publisher }}</p> <p>Date of Publication: {{ book.pubdate|date }}</p> <p>Price ${{ book.price }}</p> <p>Author : {% for a in book.authors.all %}{{ a.name }}{% if not forloop.last %}, {% endif %}{% endfor %}</p> {% endfor %} {% endblock %}
  • 20. Security advantages ‣ No raw SQL from the users ‣ We deal with models and queries ‣ Automatic HTML escaping ‣ No XSS attacks ‣ CSRF protection ‣ No replay of forms by other code
  • 22. URLs urlpatterns = patterns('apps.tutorial.views', (r'^$', 'index'), (r’^book/<?P<id>d+)/$’, ‘show_book’), (r'^latest/(?P<num_days>d+)/$', 'view_latest_books'), (r'^create/$', 'create'), ) ‣ URLs map to views (via regular expressions)
  • 24. Views are just python functions import datetime def view_latest_books(request, num_days): date = datetime.datetime.now() - datetime.timedelta(int(num_days)) books = Book.objects.filter(pubdate__gte = date).order_by('-pubdate') return render_to_response('books/show_books.html', {'books': books})
  • 25. Aggregation ‣ When you need to summarise a collection of objects ‣ Leveraging the DB where possible > q = Book.objects.annotate(num_authors=Count('authors')) > [b.num_authors for b in q] [2, 3, 1] > Store.objects.aggregate(min_price=Min('books__price'), max_price=Max('books__price')) {‘min_price’ : 2.99, ‘max_price’ : 29.99} http://docs.djangoproject.com/en/dev/topics/db/aggregation/
  • 26. Other features ‣ Forms ‣ Generic Views ‣ Makes CRUD simple ‣ User management ‣ i18n
  • 28. Projects contain Applications Project my myapp other_app reuseable app ‣ Application : self-contained set of functions ‣ Project : collection of applications, installed into same database ‣ roughly project == a web application - has a settings ïŹle
  • 29. Getting started ‣ Install Django 1.1 > easy_install django ‣ Create a project > django-admin.py startproject new_django_project new_django_project/ __init__.py manage.py settings.py urls.py
  • 30. > ./manage.py startapp tutorial new_django_project/ __init__.py manage.py settings.py tutorial/ __init__.py models.py tests.py views.py urls.py
  • 31. > ./manage.py runserver Validating models... 0 errors found Django version 1.1, using settings 'new_django_project.settings' Development server is running at http://127.0.0.1:8000/ Quit the server with CONTROL-C. ... ‣ Now you write your code ... > ./manage.py syncdb Creating table django_content_type Creating table django_session Creating table django_site Creating table tutorial_author Creating table tutorial_publisher Creating table tutorial_book Creating table tutorial_store Installing index for tutorial.Book model
  • 32. automatic admin interface http://localhost:8000/admin/tutorial/
  • 33. manage.py ‣ syncdb : create SQL for your models ‣ shell : start up a python shell with your django project loaded ‣ test : run your unit tests ‣ you did write some, didn’t you ? ‣ inspectdb : reverse engineer models for existing DB ‣ loaddata / dumpdata : load/dump your ïŹxtures from a DB
  • 34. Tools to make you more productive all just an easy_install away
  • 35. distutils ‣ ‘standard’ python packaging ‣ ./setup.py sdist : source packages ‣ /.setup.py bdist : binary packages ‣ Nice to integrate with other tools ‣ pip, unittest, ... ‣ ./setup.py bdist_rpm : Can produce rpm
  • 36. Virtualenv ‣ Run separate python environments ‣ With different sets of packages ‣ And even different interpreters ‣ Easily switch between then ‣ virtualenv_wrapper gives nice bash functions for it all http://pypi.python.org/pypi/virtualenv
  • 37. ipython ‣ python with CLI hotness ‣ TAB autocomplete ‣ code coloring ‣ nicer pdb integration ‣ ... http://ipython.scipy.org/moin/
  • 39. PIP ‣ Better installation manager ‣ ‘easy_install’ with dependency ordering ‣ Integrated with virtualenv ‣ Allow to ‘freeze’ a set of packages ‣ and re-install to the same level http://pypi.python.org/pypi/pip
  • 41. django-command-extensions ‣ Extra manage.py commands ‣ shell_plus : a better python shell ‣ runserver_plus : a better debugging server (werkzeug) ‣ show_urls : dump the url map of your site
  • 43. and of course, unittest ‣ Django supports : ‣ doctest : useful for simple model validation ‣ unittest : you did write some, didn’t you ? ‣ test client : acts a dummy web browser ‣ Test your views ‣ ïŹxture loading : have a set of complex test data ‣ generated from your production database
  • 44. reusable apps if it’s useful, it’s probably been done before...
  • 45. south ‣ Schema migration ‣ Change models over time ‣ Write upgrade routines ‣ just python functions with access to .objects and .old_objects
  • 46. A platform for rapidly developing (social) websites
  • 47. code.google.com ‣ just search for django-<WHATEVER> :) ‣ It’s probably there... ‣ If it’s not there, write it and put it there
  • 49. Multi-DB ‣ Allows your models to be in multiple DBs ‣ Different applications in different DBs ‣ ‘sharding’ of objects across DBs ‣ using slaves for read-only operations
  • 50. Other ‣ Admin UI enhancements ‣ autocompletion ‣ better inline handling ‣ Non-relational database support ‣ CouchDB, MongoDB, tokyo Tyrant, Google Bigtable, SimpleDB
  • 52. ‣ http://docs.djangoproject.com/ ‣ Django community RSS feed ‣ http://www.djangoproject.com/community/ ‣ Mailing lists ‣ django-dev to understand how the developers think ‣ django-users to ask for help ‣ DjangoCon presentations ‣ http://www.djangocon.org/
  • 53. Books
  • 56. Credits ‣ XKCD for cartoons ‣ Amazon.com for book pictures ‣ Initial inspiration for slides and examples from Joaquim Rocha, Abe Estrada ‣ http://www.slideshare.net/j_rocha/django-intro ‣ http://www.slideshare.net/AbeEstrada/django-web-framework-presentation-822177 ‣ http://www.djangoproject.com/