ºÝºÝߣ

ºÝºÝߣShare a Scribd company logo
Web Development With Django




            A Basic Introduction




                                   Ganga L
Python Frameworks

 ª«   Django
 ª«   CherryPy
 ª«   Pylons
 ª«   Flask
 ª«   Bottle
 ª«   Tipfy
 ª«   Pyramid
 ª«   Cubic Web
 ª«   GAE framework
Outline



ª«   What Is Django?
ª«   Project Structure
ª«   Data Handling
ª«   The Admin Interface
ª«   Django Forms
ª«   Views
ª«   Templates
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 . . .
Creating Projects & Apps


ª«   Creating a project:
        django-admin.py startproject mysite
ª«   Creating an app within a project directory:
         cd mysite
         ./manage.py startapp poll
Project Structure


ª«   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 apps
App

ª«   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
Up & Running

ª«   Set PYTHONPATH to include parent of your project directory
ª«   Define new environment variable DJANGO_SETTINGS_MODULE,

       setting it to project settings   (mysite.settings)
ª«   3 Try running the development server:
       /manage.py runserver
Creating The Database


ª«   Create database polls in youe database
ª«   Sync installed apps with database:
       ./manage.py syncdb
Create Project

ª«   Create Project mysite
       mysite/
         manage.py
         mysite/
            __init__.py
            settings.py
            urls.py
Create Application

ª«   python manage.py startapp polls
       polls/
         __init__.py
         models.py
         tests.py
         views.py
Create Models

 from django.db import models

 class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

 class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
The 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 . . .
Installed App

  INSTALLED_APPS = (
      'django.contrib.admin',
      'django.contrib.auth',
      'django.contrib.contenttypes',
      'django.contrib.sessions',
      'django.contrib.messages',
      'django.contrib.staticfiles',
      'polls',
  )


  python manage.py syncdb
Registering Models in Admin


ª«     In admin.py in the Poll app:

    from django.contrib import admin
    from mysite.polls.models import Poll

    admin.site.register(Poll)
In urls.py:

  from django.conf.urls import patterns, include, url

  from django.contrib import admin
  admin.autodiscover()

  urlpatterns = patterns('',
     url(/slideshow/django-ppt/18985404/r&)),
  )
Generic Views


ª«   Provide 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)
Generic Views Example

ª«   views.py
    def index(request):
      return HttpResponse("Hello, world. You're at the poll index.")
ª«   Url.py
     from django.conf.urls.defaults import *
     from polls import views

     urlpatterns = patterns('',
                              url(/slideshow/django-ppt/18985404/r&)
                             )
ª«   Main URL.py
     from django.conf.urls import patterns, include, url

     from django.contrib import admin
     admin.autodiscover()

     urlpatterns = patterns('',
                             url(/slideshow/django-ppt/18985404/r&)),
                             url(/slideshow/django-ppt/18985404/r&)),
     )
Creating & Saving Objects


 ª«   Invoke constructor and call save method:
 ª«   call create method of Club model manager:


poll = Poll(question='what is your DOB? ', year='1986)
poll.save()



Poll.objects.create(question='what is your DOB? ', year='1986)
View Function


ª«   Takes an HTTPRequest object as a parameter
ª«   Returns an HTTPResponse object to caller
ª«   Is associated with a particular URL via the URLconf
HTTP Response


from datetime import date
from django.http import HttpResponse

def today(request):
     html = '<html><body><h2>%s</h2></body></html>' % date.today()
     return HttpResponse(html)




from django.shortcuts import render_to_response
From mysite.polls.models import Poll

def poll_details(request):
     today = date.today()
     poll_data = Poll.objects.all()
     return render_to_response('clubs.html', locals(), context_instance =
                                                                      RequestContext(request))
Templates

 ª«   Text 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 %}
Template Example

settings.py

TEMPLATE_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 %}
Django Forms

ª«    A collection of fields that knows how to validate itself and display
     itself as HTML.
ª«    Display an HTML form with automatically generated form widgets.
ª«    Check submitted data against a set of validation rules.
ª«    Redisplay a form in the case of validation errors.
ª«    Convert submitted form data to the relevant Python data types.
Django Model Forms

  from django.forms import ModelForm
  import mysite.polls.models import Poll


  class PollForm(ModelForm):
     class Meta:
        model = Pole
A Basic Django Forms
Standard Views.py
Standard Views.py
Standard Views.py
Easy Views.py
Easy Views.py
Summary


ª«   We 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
Thank You

More Related Content

What's hot (20)

Web Development with Python and Django
Web Development with Python and DjangoWeb Development with Python and Django
Web Development with Python and Django
Michael Pirnat
?
Introduction to django
Introduction to djangoIntroduction to django
Introduction to django
Ilian Iliev
?
Introduction to django framework
Introduction to django frameworkIntroduction to django framework
Introduction to django framework
Knoldus Inc.
?
django
djangodjango
django
Mohamed Essam
?
Python/Flask Presentation
Python/Flask PresentationPython/Flask Presentation
Python/Flask Presentation
Parag Mujumdar
?
Flask ¨C Python
Flask ¨C PythonFlask ¨C Python
Flask ¨C Python
Max Claus Nunes
?
Django Seminar
Django SeminarDjango Seminar
Django Seminar
Yokesh Rana
?
Json
JsonJson
Json
krishnapriya Tadepalli
?
Django Tutorial | Django Web Development With Python | Django Training and Ce...
Django Tutorial | Django Web Development With Python | Django Training and Ce...Django Tutorial | Django Web Development With Python | Django Training and Ce...
Django Tutorial | Django Web Development With Python | Django Training and Ce...
Edureka!
?
Angular 8
Angular 8 Angular 8
Angular 8
Sunil OS
?
Django Girls Tutorial
Django Girls TutorialDjango Girls Tutorial
Django Girls Tutorial
Kishimi Ibrahim Ishaq
?
Server Side Programming
Server Side ProgrammingServer Side Programming
Server Side Programming
Milan Thapa
?
Introduction Django
Introduction DjangoIntroduction Django
Introduction Django
Wade Austin
?
Model View Controller (MVC)
Model View Controller (MVC)Model View Controller (MVC)
Model View Controller (MVC)
Javier Antonio Humar¨¢n Pe?u?uri
?
Basic Python Django
Basic Python DjangoBasic Python Django
Basic Python Django
Kaleem Ullah Mangrio
?
Php mysql ppt
Php mysql pptPhp mysql ppt
Php mysql ppt
Karmatechnologies Pvt. Ltd.
?
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy
?
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
Edureka!
?
Introduction to Django REST Framework, an easy way to build REST framework in...
Introduction to Django REST Framework, an easy way to build REST framework in...Introduction to Django REST Framework, an easy way to build REST framework in...
Introduction to Django REST Framework, an easy way to build REST framework in...
Zhe Li
?
An Introduction To REST API
An Introduction To REST APIAn Introduction To REST API
An Introduction To REST API
Aniruddh Bhilvare
?
Web Development with Python and Django
Web Development with Python and DjangoWeb Development with Python and Django
Web Development with Python and Django
Michael Pirnat
?
Introduction to django
Introduction to djangoIntroduction to django
Introduction to django
Ilian Iliev
?
Introduction to django framework
Introduction to django frameworkIntroduction to django framework
Introduction to django framework
Knoldus Inc.
?
Python/Flask Presentation
Python/Flask PresentationPython/Flask Presentation
Python/Flask Presentation
Parag Mujumdar
?
Django Tutorial | Django Web Development With Python | Django Training and Ce...
Django Tutorial | Django Web Development With Python | Django Training and Ce...Django Tutorial | Django Web Development With Python | Django Training and Ce...
Django Tutorial | Django Web Development With Python | Django Training and Ce...
Edureka!
?
Server Side Programming
Server Side ProgrammingServer Side Programming
Server Side Programming
Milan Thapa
?
Introduction Django
Introduction DjangoIntroduction Django
Introduction Django
Wade Austin
?
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy
?
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
Edureka!
?
Introduction to Django REST Framework, an easy way to build REST framework in...
Introduction to Django REST Framework, an easy way to build REST framework in...Introduction to Django REST Framework, an easy way to build REST framework in...
Introduction to Django REST Framework, an easy way to build REST framework in...
Zhe Li
?

Viewers also liked (13)

The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
fishwarter
?
§¡§ß§Õ§â§Ö§Û §¬§à§Ý§Ö§ê§Ü§à ?§¹§ä§à §ß§Ö §ä§Ñ§Ü §ã Rails?
§¡§ß§Õ§â§Ö§Û §¬§à§Ý§Ö§ê§Ü§à ?§¹§ä§à §ß§Ö §ä§Ñ§Ü §ã Rails?§¡§ß§Õ§â§Ö§Û §¬§à§Ý§Ö§ê§Ü§à ?§¹§ä§à §ß§Ö §ä§Ñ§Ü §ã Rails?
§¡§ß§Õ§â§Ö§Û §¬§à§Ý§Ö§ê§Ü§à ?§¹§ä§à §ß§Ö §ä§Ñ§Ü §ã Rails?
Olga Lavrentieva
?
Building a Dynamic Website Using Django
Building a Dynamic Website Using DjangoBuilding a Dynamic Website Using Django
Building a Dynamic Website Using Django
Nathan Eror
?
Introduction to django
Introduction to djangoIntroduction to django
Introduction to django
Sreenath Ramamoorthi
?
Kivy - Python UI Library for Any Platform
Kivy - Python UI Library for Any PlatformKivy - Python UI Library for Any Platform
Kivy - Python UI Library for Any Platform
Saurav Singhi
?
§£§Ó§Ö§Õ§Ö§ß§Ú§Ö §Ó Django
§£§Ó§Ö§Õ§Ö§ß§Ú§Ö §Ó Django§£§Ó§Ö§Õ§Ö§ß§Ú§Ö §Ó Django
§£§Ó§Ö§Õ§Ö§ß§Ú§Ö §Ó Django
§ª§Ý§î§ñ §¢§Ñ§â§í§ê§Ö§Ó
?
Building Pluggable Web Applications using Django
Building Pluggable Web Applications using DjangoBuilding Pluggable Web Applications using Django
Building Pluggable Web Applications using Django
Lakshman Prasad
?
§£§Ó§Ö§Õ§Ö§ß§Ú§Ö §Ó Python §Ú Django
§£§Ó§Ö§Õ§Ö§ß§Ú§Ö §Ó Python §Ú Django§£§Ó§Ö§Õ§Ö§ß§Ú§Ö §Ó Python §Ú Django
§£§Ó§Ö§Õ§Ö§ß§Ú§Ö §Ó Python §Ú Django
Taras Lyapun
?
Django in the Real World
Django in the Real WorldDjango in the Real World
Django in the Real World
Jacob Kaplan-Moss
?
?? ??? Django
?? ??? Django?? ??? Django
?? ??? Django
Taehoon Kim
?
Scalable Django Architecture
Scalable Django ArchitectureScalable Django Architecture
Scalable Django Architecture
Rami Sayar
?
The Django Web Application Framework
The Django Web Application FrameworkThe Django Web Application Framework
The Django Web Application Framework
Simon Willison
?
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
fishwarter
?
§¡§ß§Õ§â§Ö§Û §¬§à§Ý§Ö§ê§Ü§à ?§¹§ä§à §ß§Ö §ä§Ñ§Ü §ã Rails?
§¡§ß§Õ§â§Ö§Û §¬§à§Ý§Ö§ê§Ü§à ?§¹§ä§à §ß§Ö §ä§Ñ§Ü §ã Rails?§¡§ß§Õ§â§Ö§Û §¬§à§Ý§Ö§ê§Ü§à ?§¹§ä§à §ß§Ö §ä§Ñ§Ü §ã Rails?
§¡§ß§Õ§â§Ö§Û §¬§à§Ý§Ö§ê§Ü§à ?§¹§ä§à §ß§Ö §ä§Ñ§Ü §ã Rails?
Olga Lavrentieva
?
Building a Dynamic Website Using Django
Building a Dynamic Website Using DjangoBuilding a Dynamic Website Using Django
Building a Dynamic Website Using Django
Nathan Eror
?
Kivy - Python UI Library for Any Platform
Kivy - Python UI Library for Any PlatformKivy - Python UI Library for Any Platform
Kivy - Python UI Library for Any Platform
Saurav Singhi
?
Building Pluggable Web Applications using Django
Building Pluggable Web Applications using DjangoBuilding Pluggable Web Applications using Django
Building Pluggable Web Applications using Django
Lakshman Prasad
?
§£§Ó§Ö§Õ§Ö§ß§Ú§Ö §Ó Python §Ú Django
§£§Ó§Ö§Õ§Ö§ß§Ú§Ö §Ó Python §Ú Django§£§Ó§Ö§Õ§Ö§ß§Ú§Ö §Ó Python §Ú Django
§£§Ó§Ö§Õ§Ö§ß§Ú§Ö §Ó Python §Ú Django
Taras Lyapun
?
Scalable Django Architecture
Scalable Django ArchitectureScalable Django Architecture
Scalable Django Architecture
Rami Sayar
?
The Django Web Application Framework
The Django Web Application FrameworkThe Django Web Application Framework
The Django Web Application Framework
Simon Willison
?

Similar to A Basic Django Introduction (20)

Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
colinkingswood
?
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
Joaquim Rocha
?
CCCDjango2010.pdf
CCCDjango2010.pdfCCCDjango2010.pdf
CCCDjango2010.pdf
jayarao21
?
django_introduction20141030
django_introduction20141030django_introduction20141030
django_introduction20141030
Kevin Wu
?
GDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App EngineGDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App Engine
Yared Ayalew
?
Django cheat sheet
Django cheat sheetDjango cheat sheet
Django cheat sheet
Lam Hoang
?
Django crush course
Django crush course Django crush course
Django crush course
Mohammed El Rafie Tarabay
?
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
Jagdeep Singh Malhi
?
Django tech-talk
Django tech-talkDjango tech-talk
Django tech-talk
dtdannen
?
Python Expense Tracker Project with Source Code.pdf
Python Expense Tracker Project with Source Code.pdfPython Expense Tracker Project with Source Code.pdf
Python Expense Tracker Project with Source Code.pdf
abhishekdf3
?
????? ?????? ????
????? ?????? ????????? ?????? ????
????? ?????? ????
railsbootcamp
?
Django Introduction Osscamp Delhi September 08 09 2007 Mir Nazim
Django Introduction Osscamp Delhi September 08 09 2007 Mir NazimDjango Introduction Osscamp Delhi September 08 09 2007 Mir Nazim
Django Introduction Osscamp Delhi September 08 09 2007 Mir Nazim
Mir Nazim
?
Django workshop : let's make a blog
Django workshop : let's make a blogDjango workshop : let's make a blog
Django workshop : let's make a blog
Pierre Sudron
?
An Introduction to Django Web Framework
An Introduction to Django Web FrameworkAn Introduction to Django Web Framework
An Introduction to Django Web Framework
David Gibbons
?
Tango with django
Tango with djangoTango with django
Tango with django
Rajan Kumar Upadhyay
?
Django
DjangoDjango
Django
Harmeet Lamba
?
Hands on django part 1
Hands on django part 1Hands on django part 1
Hands on django part 1
MicroPyramid .
?
A gentle intro to the Django Framework
A gentle intro to the Django FrameworkA gentle intro to the Django Framework
A gentle intro to the Django Framework
Ricardo Soares
?
Django tutorial 2009
Django tutorial 2009Django tutorial 2009
Django tutorial 2009
Ferenc Szalai
?
Mini Curso de Django
Mini Curso de DjangoMini Curso de Django
Mini Curso de Django
Felipe Queiroz
?
CCCDjango2010.pdf
CCCDjango2010.pdfCCCDjango2010.pdf
CCCDjango2010.pdf
jayarao21
?
django_introduction20141030
django_introduction20141030django_introduction20141030
django_introduction20141030
Kevin Wu
?
GDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App EngineGDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App Engine
Yared Ayalew
?
Django cheat sheet
Django cheat sheetDjango cheat sheet
Django cheat sheet
Lam Hoang
?
Django tech-talk
Django tech-talkDjango tech-talk
Django tech-talk
dtdannen
?
Python Expense Tracker Project with Source Code.pdf
Python Expense Tracker Project with Source Code.pdfPython Expense Tracker Project with Source Code.pdf
Python Expense Tracker Project with Source Code.pdf
abhishekdf3
?
Django Introduction Osscamp Delhi September 08 09 2007 Mir Nazim
Django Introduction Osscamp Delhi September 08 09 2007 Mir NazimDjango Introduction Osscamp Delhi September 08 09 2007 Mir Nazim
Django Introduction Osscamp Delhi September 08 09 2007 Mir Nazim
Mir Nazim
?
Django workshop : let's make a blog
Django workshop : let's make a blogDjango workshop : let's make a blog
Django workshop : let's make a blog
Pierre Sudron
?
An Introduction to Django Web Framework
An Introduction to Django Web FrameworkAn Introduction to Django Web Framework
An Introduction to Django Web Framework
David Gibbons
?
A gentle intro to the Django Framework
A gentle intro to the Django FrameworkA gentle intro to the Django Framework
A gentle intro to the Django Framework
Ricardo Soares
?

A Basic Django Introduction

  • 1. Web Development With Django A Basic Introduction Ganga L
  • 2. Python Frameworks ª« Django ª« CherryPy ª« Pylons ª« Flask ª« Bottle ª« Tipfy ª« Pyramid ª« Cubic Web ª« GAE framework
  • 3. Outline ª« What Is Django? ª« Project Structure ª« Data Handling ª« The Admin Interface ª« Django Forms ª« Views ª« Templates
  • 4. 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 . . .
  • 5. Creating Projects & Apps ª« Creating a project: django-admin.py startproject mysite ª« Creating an app within a project directory: cd mysite ./manage.py startapp poll
  • 6. Project Structure ª« 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 apps
  • 7. App ª« 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
  • 8. Up & Running ª« Set PYTHONPATH to include parent of your project directory ª« Define new environment variable DJANGO_SETTINGS_MODULE, setting it to project settings (mysite.settings) ª« 3 Try running the development server: /manage.py runserver
  • 9. Creating The Database ª« Create database polls in youe database ª« Sync installed apps with database: ./manage.py syncdb
  • 10. Create Project ª« Create Project mysite mysite/ manage.py mysite/ __init__.py settings.py urls.py
  • 11. Create Application ª« python manage.py startapp polls polls/ __init__.py models.py tests.py views.py
  • 12. Create Models from django.db import models class Poll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): poll = models.ForeignKey(Poll) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0)
  • 13. The 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 . . .
  • 14. Installed App INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls', ) python manage.py syncdb
  • 15. Registering Models in Admin ª« In admin.py in the Poll app: from django.contrib import admin from mysite.polls.models import Poll admin.site.register(Poll)
  • 16. In urls.py: from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(/slideshow/django-ppt/18985404/r&)), )
  • 17. Generic Views ª« Provide 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)
  • 18. Generic Views Example ª« views.py def index(request): return HttpResponse("Hello, world. You're at the poll index.") ª« Url.py from django.conf.urls.defaults import * from polls import views urlpatterns = patterns('', url(/slideshow/django-ppt/18985404/r&) ) ª« Main URL.py from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(/slideshow/django-ppt/18985404/r&)), url(/slideshow/django-ppt/18985404/r&)), )
  • 19. Creating & Saving Objects ª« Invoke constructor and call save method: ª« call create method of Club model manager: poll = Poll(question='what is your DOB? ', year='1986) poll.save() Poll.objects.create(question='what is your DOB? ', year='1986)
  • 20. View Function ª« Takes an HTTPRequest object as a parameter ª« Returns an HTTPResponse object to caller ª« Is associated with a particular URL via the URLconf
  • 21. HTTP Response from datetime import date from django.http import HttpResponse def today(request): html = '<html><body><h2>%s</h2></body></html>' % date.today() return HttpResponse(html) from django.shortcuts import render_to_response From mysite.polls.models import Poll def poll_details(request): today = date.today() poll_data = Poll.objects.all() return render_to_response('clubs.html', locals(), context_instance = RequestContext(request))
  • 22. Templates ª« Text 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 %}
  • 23. Template Example settings.py TEMPLATE_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 %}
  • 24. Django Forms ª« A collection of fields that knows how to validate itself and display itself as HTML. ª« Display an HTML form with automatically generated form widgets. ª« Check submitted data against a set of validation rules. ª« Redisplay a form in the case of validation errors. ª« Convert submitted form data to the relevant Python data types.
  • 25. Django Model Forms from django.forms import ModelForm import mysite.polls.models import Poll class PollForm(ModelForm): class Meta: model = Pole
  • 26. A Basic Django Forms
  • 32. Summary ª« We 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