Slides

  • 1,852 views
Uploaded on

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

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

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
  • Great tutorial!
    Thank you.
    Are you sure you want to
    Your message goes here
No Downloads

Views

Total Views
1,852
On Slideshare
0
From Embeds
0
Number of Embeds
1

Actions

Shares
Downloads
67
Comments
1
Likes
2

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. 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
  • 2. 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
  • 3. 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
  • 4. 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
  • 5. 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
  • 6. 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
  • 7. 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
  • 8. 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
  • 9. 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
  • 10. 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
  • 11. 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
  • 12. 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
  • 13. 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
  • 14. 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
  • 15. 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
  • 16. 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
  • 17. 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
  • 18. 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
  • 19. 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
  • 20. 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
  • 21. 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
  • 22. 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
  • 23. 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
  • 24. 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
  • 25. 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
  • 26. 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
  • 27. 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
  • 28. 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
  • 29. Getting Started The Admin InterfaceThe Admin Interface Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 22 / 31
  • 30. 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
  • 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
  • 32. 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
  • 33. 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
  • 34. 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
  • 35. 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
  • 36. 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
  • 37. 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
  • 38. 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
  • 39. 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
  • 40. 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
  • 41. 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
  • 42. 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
  • 43. 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
  • 44. 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
  • 45. 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
  • 46. 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
  • 47. 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
  • 48. 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
  • 49. 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