Slides
Upcoming SlideShare
Loading in...5
×
 

Slides

on

  • 2,233 views

An introduction to the core features of the Django web development framework.

An introduction to the core features of the Django web development framework.

Statistics

Views

Total Views
2,233
Views on SlideShare
2,226
Embed Views
7

Actions

Likes
2
Downloads
67
Comments
1

3 Embeds 7

http://www.sit-ec.net 3
https://www.linkedin.com 3
http://www.linkedin.com 1

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
  • Great tutorial!
    Thank you.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Slides Slides Presentation Transcript

  • Web Development With Django A Basic Introduction Nick Efford nick.efford@gmail.com pythoneering.blogspot.com twitter.com/python33r School of Computing University of Leeds YPy Workshop, 11 December 2010Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 1 / 31
  • Outline1 Introduction Setting Up What Is Django?2 Getting Started Project Structure Data Handling The Admin Interface3 Front-End Development Views Templates Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 2 / 31
  • Introduction Setting UpOutline1 Introduction Setting Up What Is Django?2 Getting Started Project Structure Data Handling The Admin Interface3 Front-End Development Views Templates Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 3 / 31
  • Introduction Setting UpFiles Required 1 Create a directory for this tutorial 2 Copy django.py and django-example.zip from the USB drive to the new directory 3 Unpack the two archives Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 4 / 31
  • Introduction Setting UpFiles Required 1 Create a directory for this tutorial 2 Copy django.py and django-example.zip from the USB drive to the new directory 3 Unpack the two archives Windows Users Avoid spaces in pathnames! Try unpacking Zip archives in C:tmppython or similar Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 4 / 31
  • Introduction Setting UpFiles Required 1 Create a directory for this tutorial 2 Copy django.py and django-example.zip from the USB drive to the new directory 3 Unpack the two archives Windows Users Avoid spaces in pathnames! Try unpacking Zip archives in C:tmppython or similar Note We assume you have Python 2.6 or 2.7 already installed . . . Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 4 / 31
  • Introduction Setting UpSetting Up DjangoDo one of the following: • In django-trunk directory (the one containing README) do python setup.py install • Set PYTHONPATH to include django-trunk directoryUse Python interpreter to verify: >>> import django >>> django.VERSION (1, 3, 0, alpha, 1) Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 5 / 31
  • Introduction What Is Django?Outline1 Introduction Setting Up What Is Django?2 Getting Started Project Structure Data Handling The Admin Interface3 Front-End Development Views Templates Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 6 / 31
  • Introduction What Is Django?What Is Django? • High-level framework for rapid web development • Complete stack of tools • Data modelled with Python classes • Production-ready data admin interface, generated dynamically • Elegant system for mapping URLs to Python code • ‘Generic views’ to handle common requests • Clean, powerful template language • Components for user authentication, form handling, caching . . . Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 7 / 31
  • Introduction What Is Django?A Working Example Football match results and league tables Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 8 / 31
  • Getting Started Project StructureOutline1 Introduction Setting Up What Is Django?2 Getting Started Project Structure Data Handling The Admin Interface3 Front-End Development Views Templates Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 9 / 31
  • Getting Started Project StructureProject StructureProject • A Python package on your PYTHONPATH • Holds project-wide settings in settings.py • Holds a URL configuration (URLconf) in urls.py • Contains or references one or more appsApp • A Python package on your PYTHONPATH (typically created as a subpackage of the project itself) • May contain data models in models.py • May contain views in views.py • May have its own URL configuration in urls.py Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 10 / 31
  • Getting Started Project StructureProject StructureProject • A Python package on your PYTHONPATH • Holds project-wide settings in settings.py • Holds a URL configuration (URLconf) in urls.py • Contains or references one or more appsApp • A Python package on your PYTHONPATH (typically created as a subpackage of the project itself) • May contain data models in models.py • May contain views in views.py • May have its own URL configuration in urls.py Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 10 / 31
  • Getting Started Project StructureCreating Projects & AppsCreating a project: django-admin.py startproject footballCreating an app within a project directory: cd football ./manage.py startapp club Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 11 / 31
  • Getting Started Project StructureUp & Running1 Set PYTHONPATH to include parent of your project directory2 Define new environment variable DJANGO_SETTINGS_MODULE, setting it to project settings (football.settings)3 Try running the development server: ./manage.py runserver Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 12 / 31
  • Getting Started Project Structuresettings.py • Database used (PostgreSQL, MySQL, Oracle, SQLite . . . ) • Which apps & middleware components are active • Paths to templates and static media • How logging is done . . . Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 13 / 31
  • Getting Started Project Structuresettings.py • Database used (PostgreSQL, MySQL, Oracle, SQLite . . . ) • Which apps & middleware components are active • Paths to templates and static media • How logging is done . . .DATABASES = { default: { ENGINE: django.db.backends.sqlite3, NAME : os.path.join(os.path.dirname(__file__), football.db), ... }}...INSTALLED_APPS = ( ... django.contrib.admin, football.club,) Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 13 / 31
  • Getting Started Data HandlingOutline1 Introduction Setting Up What Is Django?2 Getting Started Project Structure Data Handling The Admin Interface3 Front-End Development Views Templates Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 14 / 31
  • Getting Started Data HandlingThe Data Model • A description of database layout, as a Python class • Normally represents one database table • Has fields that map onto columns of the table • Many built-in field types • CharField, TextField • IntegerField, FloatField, DecimalField • DateField, DateTimeField, TimeField • EmailField, URLField • ForeignKey . . . Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 15 / 31
  • Getting Started Data HandlingExamplefrom django.db import modelsclass Club(models.Model): """A football club.""" name = models.CharField(max_length=30) year_established = models.PositiveSmallIntegerField() ground = models.CharField(max_length=30) class Meta: ordering = (name,) def __unicode__(self): return self.name Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 16 / 31
  • Getting Started Data HandlingCreating The Database1 Optionally check table creation SQL: ./manage.py sql club2 Sync installed apps with database: ./manage.py syncdb3 Optionally check the outcome in the database: ./manage.py dbshell4 Populate the database Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 17 / 31
  • Getting Started Data HandlingCreating & Saving ObjectsInvoke constructor and call save method:club = Club(name=Arsenal, year_established=1886, ground=Emirates Stadium)club.save() Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 18 / 31
  • Getting Started Data HandlingCreating & Saving ObjectsInvoke constructor and call save method:club = Club(name=Arsenal, year_established=1886, ground=Emirates Stadium)club.save(). . . or call create method of Club model manager:Club.objects.create(name=Arsenal, year_established=1886, ground=Emirates Stadium) Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 18 / 31
  • Getting Started Data HandlingRetrieving ObjectsRetrieve a single object with get:club = Club.objects.get(name=Liverpool) Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 19 / 31
  • Getting Started Data HandlingRetrieving ObjectsRetrieve a single object with get:club = Club.objects.get(name=Liverpool)Retrieve querysets with all, filter, etc:for club in Club.objects.all(): print clubfor club in Club.objects.filter(year_established=1878): print club Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 19 / 31
  • Getting Started The Admin InterfaceOutline1 Introduction Setting Up What Is Django?2 Getting Started Project Structure Data Handling The Admin Interface3 Front-End Development Views Templates Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 20 / 31
  • Getting Started The Admin InterfaceRegistering ModelsIn admin.py in the club app:from django.contrib import adminfrom football.club.models import Clubadmin.site.register(Club) Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 21 / 31
  • Getting Started The Admin InterfaceRegistering ModelsIn admin.py in the club app:from django.contrib import adminfrom football.club.models import Clubadmin.site.register(Club)In top-level urls.py:from django.contrib import adminadmin.autodiscover()urlpatterns = patterns(, (r^admin/, include(admin.site.urls)), (r^clubs/, include(football.club.urls)), ...) Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 21 / 31
  • Getting Started The Admin InterfaceThe Admin Interface Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 22 / 31
  • Front-End Development ViewsOutline1 Introduction Setting Up What Is Django?2 Getting Started Project Structure Data Handling The Admin Interface3 Front-End Development Views Templates Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 23 / 31
  • Front-End Development ViewsGeneric ViewsProvide ready-made logic for many common tasks: • Issuing a redirect • Displaying a paginated list of objects • Displaying a ‘detail’ page for a single object • Yearly, monthly or daily listing of date-based objects • ‘Latest items’ page for date-based objects • Object creation, updating, deletion (with/without authorisation) Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 24 / 31
  • Front-End Development ViewsGeneric Views Exampleviews.pyfrom django.views.generic import ListViewfrom football.club.models import Clubclass ClubListView(ListView): model = Club context_object_name = clubs Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 25 / 31
  • Front-End Development ViewsGeneric Views Exampleviews.pyfrom django.views.generic import ListViewfrom football.club.models import Clubclass ClubListView(ListView): model = Club context_object_name = clubsurls.pyfrom django.conf.urls.defaults import *from football.club.views import ClubListViewurlpatterns = patterns(, (r^$, ClubListView.as_view()), ...) Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 25 / 31
  • Front-End Development ViewsView Function • Takes an HTTPRequest object as a parameter • Returns an HTTPResponse object to caller • Is associated with a particular URL via the URLconf Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 26 / 31
  • Front-End Development ViewsView Function • Takes an HTTPRequest object as a parameter • Returns an HTTPResponse object to caller • Is associated with a particular URL via the URLconffrom datetime import datefrom django.http import HttpResponsedef today(request): html = <html><body><h2>%s</h2></body></html> % date.today() return HttpResponse(html) Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 26 / 31
  • Front-End Development ViewsView Function • Takes an HTTPRequest object as a parameter • Returns an HTTPResponse object to caller • Is associated with a particular URL via the URLconffrom datetime import datefrom django.http import HttpResponsedef today(request): html = <html><body><h2>%s</h2></body></html> % date.today() return HttpResponse(html)from django.shortcuts import render_to_responsefrom football.club.models import Clubdef clubs(request): data = { clubs: Club.objects.all() } return render_to_response(clubs.html, data) Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 26 / 31
  • Front-End Development TemplatesOutline1 Introduction Setting Up What Is Django?2 Getting Started Project Structure Data Handling The Admin Interface3 Front-End Development Views Templates Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 27 / 31
  • Front-End Development TemplatesTemplatesText files containing • Variables, replaced by values when the template is rendered {{ today }} • Filters that modify how values are displayed {{ today|date:"D d M Y" }} • Tags that control the logic of the rendering process {% if name == "nick" %} <p>Hello, Nick!</p> {% else %} <p>Who are you?</p> {% endif %}Django comes with a large collection of useful tags & filters, and youcan also define your own . . . Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 28 / 31
  • Front-End Development TemplatesTemplate Examplesettings.pyTEMPLATE_DIRS = ( os.path.join(os.path.dirname(__file__), templates),) Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 29 / 31
  • Front-End Development TemplatesTemplate Examplesettings.pyTEMPLATE_DIRS = ( os.path.join(os.path.dirname(__file__), templates),)templates/club/club_list.html{% extends "base.html" %}{% block title %}Clubs{% endblock %}{% block content %} <h1>Clubs</h1> <ol> {% for club in clubs %} <li>{{ club }}</li> {% endfor %} </ol>{% endblock %} Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 29 / 31
  • Final ThoughtsSummaryWe have shown you • The structure of a Django project • How models represent data in Django applications • How data can be stored and queried via model instances • How data can be managed through a dynamic admin interface • How functionality is represent by views, each associated with URLs that match a given pattern • How views render a response using a template Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 30 / 31
  • Final ThoughtsSummaryWe have shown you • The structure of a Django project • How models represent data in Django applications • How data can be stored and queried via model instances • How data can be managed through a dynamic admin interface • How functionality is represent by views, each associated with URLs that match a given pattern • How views render a response using a template Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 30 / 31
  • Final ThoughtsSummaryWe have shown you • The structure of a Django project • How models represent data in Django applications • How data can be stored and queried via model instances • How data can be managed through a dynamic admin interface • How functionality is represent by views, each associated with URLs that match a given pattern • How views render a response using a template Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 30 / 31
  • Final ThoughtsSummaryWe have shown you • The structure of a Django project • How models represent data in Django applications • How data can be stored and queried via model instances • How data can be managed through a dynamic admin interface • How functionality is represent by views, each associated with URLs that match a given pattern • How views render a response using a template Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 30 / 31
  • Final ThoughtsSummaryWe have shown you • The structure of a Django project • How models represent data in Django applications • How data can be stored and queried via model instances • How data can be managed through a dynamic admin interface • How functionality is represent by views, each associated with URLs that match a given pattern • How views render a response using a template Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 30 / 31
  • Final ThoughtsSummaryWe have shown you • The structure of a Django project • How models represent data in Django applications • How data can be stored and queried via model instances • How data can be managed through a dynamic admin interface • How functionality is represent by views, each associated with URLs that match a given pattern • How views render a response using a template Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 30 / 31
  • Final ThoughtsSummaryWe have shown you • The structure of a Django project • How models represent data in Django applications • How data can be stored and queried via model instances • How data can be managed through a dynamic admin interface • How functionality is represent by views, each associated with URLs that match a given pattern • How views render a response using a template Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 30 / 31
  • Final ThoughtsSummaryWe have shown you • The structure of a Django project • How models represent data in Django applications • How data can be stored and queried via model instances • How data can be managed through a dynamic admin interface • How functionality is represent by views, each associated with URLs that match a given pattern • How views render a response using a template Hopefully, you now have a sense of what it is like to develop web applications in Django! Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 30 / 31
  • Final ThoughtsFinding Out More • Project home http://www.djangoproject.com/ • Sites built using Django http://djangosites.org/ • Django developers http://djangopeople.net/ • Django-based rapid development platform http://pinaxproject.com/ • Apress books (http://www.apress.com/) • The Definitive Guide to Django (2nd edition) • Practical Django Projects (2nd edition) • Pro Django • Beginning Django E-Commerce Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 31 / 31