SlideShare uma empresa Scribd logo
1 de 38
The Django Web Application
        Framework


                     zhixiong.hong
                       2009.3.26
Outline
 Overview
 Architecture
 Modules
 Example
 Links
Outline
 Overview
 Architecture
 Example
 Modules
 Links
Web Application Framework
 Define
  “A software framework that is designed to support the development of
     dynamic website, Web applications and Web services”(from wikipedia)
 The ideal framework
   Clean URLs
   Loosely coupled components
   Designer-friendly templates
   As little code as possible
   Really fast development
Web Application Framework(cont..)
 Ruby
  Ruby on Rails (famous, beauty)
 Python
  Django, TurboGears, Pylons, Zope, Quixote,web2py(simple)
 PHP
  CakePHP, CodeIgniter, PRADO, ThinkPHP,QeePHP (poor performance)
 Others
  Apache, J2EE, .NET...(complex)
Web Application Framework(cont..)
Comparsion
What a Django
 “Django is a high-level Python web framework that
  encourages rapid development and clean, pragmatic
  design.”
 Primary Focus
   Dynamic and database driven website
   Content based websites
Django History
 Named after famous Guitarist “Django Reinhardt”
 Developed by Adrian Holovaty & Jacob Kaplan-moss
 Open sourced in 2005
 1.0 Version released Sep.3 2008, now 1.1 Beta
Why Use Django
 Lets you divide code modules into logical groups to make it flexible
  to change
   MVC design pattern (MVT)
 Provides auto generated web admin to ease the website
  administration
 Provides pre-packaged API for common user tasks
 Provides you template system to define HTML template for your
  web pages to avoid code duplication
   DRY Principle
 Allows you to define what URL be for a given Function
   Loosely Coupled Principle
 Allows you to separate business logic from the HTML
   Separation of concerns
 Everything is in python (schema/settings)
Outline
 Overview
 Architecture
 Modules
 Example
 Links
Django as an MVC Design Pattern
  MVT Architecture:
   Models
    Describes your data structure/database schema
   Views
     Controls what a user sees
   Templates
     How a user sees it
   Controller
     The Django Framework
     URL dispatcher
Architecture Diagram

                    Brower



         Template              URL dispatcher



                     View



                     Model



                    DataBase
Model

                   Brower



        Template              URL dispatcher



                    View



                    Model



                   DataBase
Model Overview
SQL Free
ORM
Relations
API
Model

  class Category(models.Model):
       name = models.CharField(max_length=200)
       slug = models.SlugField(unique=True)



  class Entry(models.Model):
       title = models.CharField(max_length=200)
       slug = models.SlugField(unique=True)
       body = models.TextField()
       data = models.DateTimeField(default=datetime.now)
       categories = models.ManyToManyField(Category)


  python manage.py syncdb
Model API
  >>> category = Category(slug='django', name='Django')
  >>> category.save()
  >>> print category.name
  u'Django'

  >>> categories = Category.objects.all()
  >>> categories = Category.objects.filter(slug='django')
  >>> categories
  [<Category: Category object>]

  >>> entry = Entry(slug='welcome', title='Welcome', body='')
  >>> entry.save()
  >>> entry.categories.add( category[0] )
  >>> print entry.categories.all()
  [<Category: Category object>]
View

                  Brower



       Template              URL dispatcher



                   View



                   Model



                  DataBase
View

  def entry_list(request):
      entries = Ebtry.objects.all()[:5]
      return render_to_response('list.html', {'entries': entries})



  def entry_details(request, slug):
       entry = get_object_or_404(Entry, slug = slug)
       return render_to_response('details.html', {'entry': entry})
Template

                      Brower



           Template              URL dispatcher



                       View



                       Model



                      DataBase
Template Syntax
 {{ variables }}, {% tags %}, filters               (list.html)

  <html>
      <head>
      <title>My Blog</title>
      </head>
      <body>
      {% for entry in entries %}
      <h1>{{ entry.title|upper }}</h1>
      {{ entry.body }}<br/>
      Published {{ entry.data|date:quot;d F Yquot; }},
      <a href=”{{ entry.get_absolute_url }}”>link</a>.
      {% endfor %}
      </body>
  </html>
Tag and Filter
 Build in Filters and Tags
 Custom tag and filter libraries
   Put logic in tags
  {% load comments %}
  <h1>{{ entry.title|upper }}</h1>
  {{ entry.body }}<br/>
  Published {{ entry.data|date:quot;d F Yquot; }},
  <a href=”{{ entry.get_absolute_url }}”>link</a>.
  <h3>评论: </h3>
  {% get_comment_list for entry as comment_list %}
  {% for comment in comment_list %}
       {{ comment.content }}
  {% endfor %}
Template Inheritance
 base.html                      index.html
  <html>
      <head>
      <title>
                                {% extend “base.html” %}
            {% block title %}
                                {% block title %}
            {% endblock %}
                                     Main page
      </title>
                                {% endblock %}
      </head>
                                {% block body %}
      <body>
                                     Content
            {% block body %}
                                {% endblock %}
            {% endblock %}
      </body>
  </html>
URL Dispatcher

                   Brower



        Template              URL Dispatcher



                    View



                    Model



                   DataBase
URL Dispatcher

  urlpatterns = patterns('',
  #http://jianghu.leyubox.com/articles/
  ((r'^articles/$', ‘article.views.index'), )

  #http://jianghu.leyubox.com/articles/2003/
  (r'^articles/(?P<year>d{4})/$', ‘article.views.year_archive'),

  # http://jianghu.leyubox.com/articles/2003/ 12/
  (r'^articles/(?P<year>d{4})/(?P<month>d{2})/$',
  'article.views.month_archive'),

  # http://jianghu.leyubox.com/articles/2003/ 12/3
  (r'^articles/(?P<year>d{4})/(?P<month>d{2})/(?P<day>d+)/$',
  'article..views.article_detail'), )
Outline
 Overview
 Architecture
 Modules
 Example
 Links
Modules
 Form
 Adminstration interface
 Custom Middleware
 Caching
 Signals
 Comments system
 More...
Modules:Form

  class ContactForm(forms.Form):
       subject = forms.CharField(max_length=100)
       message = forms.CharField(widget=forms.Textarea)
       sender = forms.EmailField()
       cc_myself = forms.BooleanField(required=False)



  <form action=quot;/contact/quot; method=quot;POSTquot;>
       {{ form.as_table}}
       <input type=quot;submitquot; value=quot;Submitquot; />
  </form>
Modules:Adminstration interface
Modules: Custom Middleware
     chain of processes


request                                                         response
           Common       Session     Authentication     Profile
          Middleware   Middleware    Middleware      Middleware
Modules: Caching


   Memcached     Database   Filesystem     Local-memory        Dummy


                            BaseCache



                                                          template caching
                                   Per-View Caching
      Per-Site Caching
Modules:More...
 Sessions
 Authentication system
 Internationalization and localization
 Syndication feeds(RSS/Atom)
 E-mail(sending)
 Pagination
 Signals
Outline
 Overview
 Architecture
 Modules
 Example
 Links
Example
 django_admin startproject leyubbs
 modify setting.py
   set database options
   append admin app: django.contrib.admin
 python manager.py syncdb
 python manager.py runserver
 modify urls.py, append /admin path
Example(cont...)
 python manager.py startapp article
 add a model
 python manager.py syncdb
 explore admin page
 inset a record in adminstration interface
 add a veiw function
 add a url
Outline
 Overview
 Architecture
 Modules
 Example
 Links
Links: Who Use
Links: Resource
 http://www.djangoproject.com/
  For more information (Documentation,Download and News)

 http://www.djangobook.com/
  A Good book to learn Django

 http://www.djangopluggables.com
  A lot of Django Pluggables available online Explore at

 http://www.pinaxproject.com/
  Community Development
Thanks (Q&A)

Mais conteúdo relacionado

Mais procurados

JavaScript and jQuery Fundamentals
JavaScript and jQuery FundamentalsJavaScript and jQuery Fundamentals
JavaScript and jQuery Fundamentals
BG Java EE Course
 
HTL(Sightly) - All you need to know
HTL(Sightly) - All you need to knowHTL(Sightly) - All you need to know
HTL(Sightly) - All you need to know
Prabhdeep Singh
 
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
 
Seo cheat sheet_2-2013
Seo cheat sheet_2-2013Seo cheat sheet_2-2013
Seo cheat sheet_2-2013
ekkarthik
 

Mais procurados (18)

Html 5 in a big nutshell
Html 5 in a big nutshellHtml 5 in a big nutshell
Html 5 in a big nutshell
 
MVC Frameworks for building PHP Web Applications
MVC Frameworks for building PHP Web ApplicationsMVC Frameworks for building PHP Web Applications
MVC Frameworks for building PHP Web Applications
 
Opening up the Social Web - Standards that are bridging the Islands
Opening up the Social Web - Standards that are bridging the IslandsOpening up the Social Web - Standards that are bridging the Islands
Opening up the Social Web - Standards that are bridging the Islands
 
JavaScript and jQuery Fundamentals
JavaScript and jQuery FundamentalsJavaScript and jQuery Fundamentals
JavaScript and jQuery Fundamentals
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginning
 
Wt unit 4 server side technology-2
Wt unit 4 server side technology-2Wt unit 4 server side technology-2
Wt unit 4 server side technology-2
 
WWW and HTTP
WWW and HTTPWWW and HTTP
WWW and HTTP
 
Css, xhtml, javascript
Css, xhtml, javascriptCss, xhtml, javascript
Css, xhtml, javascript
 
Realize mais com HTML 5 e CSS 3 - 16 EDTED - RJ
Realize mais com HTML 5 e CSS 3 - 16 EDTED - RJRealize mais com HTML 5 e CSS 3 - 16 EDTED - RJ
Realize mais com HTML 5 e CSS 3 - 16 EDTED - RJ
 
HTML 5 Step By Step - Ebook
HTML 5 Step By Step - EbookHTML 5 Step By Step - Ebook
HTML 5 Step By Step - Ebook
 
HTL(Sightly) - All you need to know
HTL(Sightly) - All you need to knowHTL(Sightly) - All you need to know
HTL(Sightly) - All you need to know
 
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
 
Django
DjangoDjango
Django
 
Integrating Plone with E-Commerce and Relationship Management: A Case Study i...
Integrating Plone with E-Commerce and Relationship Management: A Case Study i...Integrating Plone with E-Commerce and Relationship Management: A Case Study i...
Integrating Plone with E-Commerce and Relationship Management: A Case Study i...
 
Seo cheat sheet_2-2013
Seo cheat sheet_2-2013Seo cheat sheet_2-2013
Seo cheat sheet_2-2013
 
CSS
CSSCSS
CSS
 
Angular js
Angular jsAngular js
Angular js
 
19servlets
19servlets19servlets
19servlets
 

Semelhante a The Django Web Application Framework 2

Intro To Mvc Development In Php
Intro To Mvc Development In PhpIntro To Mvc Development In Php
Intro To Mvc Development In Php
funkatron
 
MVC & SQL_In_1_Hour
MVC & SQL_In_1_HourMVC & SQL_In_1_Hour
MVC & SQL_In_1_Hour
Dilip Patel
 
django_introduction20141030
django_introduction20141030django_introduction20141030
django_introduction20141030
Kevin Wu
 
WRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptx
WRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptxWRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptx
WRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptx
salemsg
 

Semelhante a The Django Web Application Framework 2 (20)

Intro To Mvc Development In Php
Intro To Mvc Development In PhpIntro To Mvc Development In Php
Intro To Mvc Development In Php
 
Introduction To ASP.NET MVC
Introduction To ASP.NET MVCIntroduction To ASP.NET MVC
Introduction To ASP.NET MVC
 
Django - Framework web para perfeccionistas com prazos
Django - Framework web para perfeccionistas com prazosDjango - Framework web para perfeccionistas com prazos
Django - Framework web para perfeccionistas com prazos
 
ASP.NET MVC introduction
ASP.NET MVC introductionASP.NET MVC introduction
ASP.NET MVC introduction
 
ActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group PresentationActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group Presentation
 
Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!
 
Boston Computing Review - Ruby on Rails
Boston Computing Review - Ruby on RailsBoston Computing Review - Ruby on Rails
Boston Computing Review - Ruby on Rails
 
PHPConf-TW 2012 # Twig
PHPConf-TW 2012 # TwigPHPConf-TW 2012 # Twig
PHPConf-TW 2012 # Twig
 
MVC & SQL_In_1_Hour
MVC & SQL_In_1_HourMVC & SQL_In_1_Hour
MVC & SQL_In_1_Hour
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's Code
 
django_introduction20141030
django_introduction20141030django_introduction20141030
django_introduction20141030
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
WRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptx
WRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptxWRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptx
WRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptx
 
Grails Introduction - IJTC 2007
Grails Introduction - IJTC 2007Grails Introduction - IJTC 2007
Grails Introduction - IJTC 2007
 
Practical catalyst
Practical catalystPractical catalyst
Practical catalyst
 
Create a web-app with Cgi Appplication
Create a web-app with Cgi AppplicationCreate a web-app with Cgi Appplication
Create a web-app with Cgi Appplication
 
Real-World AJAX with ASP.NET
Real-World AJAX with ASP.NETReal-World AJAX with ASP.NET
Real-World AJAX with ASP.NET
 
Introduction To Code Igniter
Introduction To Code IgniterIntroduction To Code Igniter
Introduction To Code Igniter
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
JBUG 11 - Django-The Web Framework For Perfectionists With Deadlines
JBUG 11 - Django-The Web Framework For Perfectionists With DeadlinesJBUG 11 - Django-The Web Framework For Perfectionists With Deadlines
JBUG 11 - Django-The Web Framework For Perfectionists With Deadlines
 

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Último (20)

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDM
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 

The Django Web Application Framework 2

  • 1. The Django Web Application Framework zhixiong.hong 2009.3.26
  • 2. Outline  Overview  Architecture  Modules  Example  Links
  • 3. Outline  Overview  Architecture  Example  Modules  Links
  • 4. Web Application Framework  Define “A software framework that is designed to support the development of dynamic website, Web applications and Web services”(from wikipedia)  The ideal framework  Clean URLs  Loosely coupled components  Designer-friendly templates  As little code as possible  Really fast development
  • 5. Web Application Framework(cont..)  Ruby Ruby on Rails (famous, beauty)  Python Django, TurboGears, Pylons, Zope, Quixote,web2py(simple)  PHP CakePHP, CodeIgniter, PRADO, ThinkPHP,QeePHP (poor performance)  Others Apache, J2EE, .NET...(complex)
  • 7. What a Django  “Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design.”  Primary Focus  Dynamic and database driven website  Content based websites
  • 8. Django History  Named after famous Guitarist “Django Reinhardt”  Developed by Adrian Holovaty & Jacob Kaplan-moss  Open sourced in 2005  1.0 Version released Sep.3 2008, now 1.1 Beta
  • 9. Why Use Django  Lets you divide code modules into logical groups to make it flexible to change MVC design pattern (MVT)  Provides auto generated web admin to ease the website administration  Provides pre-packaged API for common user tasks  Provides you template system to define HTML template for your web pages to avoid code duplication DRY Principle  Allows you to define what URL be for a given Function Loosely Coupled Principle  Allows you to separate business logic from the HTML Separation of concerns  Everything is in python (schema/settings)
  • 10. Outline  Overview  Architecture  Modules  Example  Links
  • 11. Django as an MVC Design Pattern MVT Architecture:  Models Describes your data structure/database schema  Views Controls what a user sees  Templates How a user sees it  Controller The Django Framework URL dispatcher
  • 12. Architecture Diagram Brower Template URL dispatcher View Model DataBase
  • 13. Model Brower Template URL dispatcher View Model DataBase
  • 15. Model class Category(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(unique=True) class Entry(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(unique=True) body = models.TextField() data = models.DateTimeField(default=datetime.now) categories = models.ManyToManyField(Category) python manage.py syncdb
  • 16. Model API >>> category = Category(slug='django', name='Django') >>> category.save() >>> print category.name u'Django' >>> categories = Category.objects.all() >>> categories = Category.objects.filter(slug='django') >>> categories [<Category: Category object>] >>> entry = Entry(slug='welcome', title='Welcome', body='') >>> entry.save() >>> entry.categories.add( category[0] ) >>> print entry.categories.all() [<Category: Category object>]
  • 17. View Brower Template URL dispatcher View Model DataBase
  • 18. View def entry_list(request): entries = Ebtry.objects.all()[:5] return render_to_response('list.html', {'entries': entries}) def entry_details(request, slug): entry = get_object_or_404(Entry, slug = slug) return render_to_response('details.html', {'entry': entry})
  • 19. Template Brower Template URL dispatcher View Model DataBase
  • 20. Template Syntax  {{ variables }}, {% tags %}, filters (list.html) <html> <head> <title>My Blog</title> </head> <body> {% for entry in entries %} <h1>{{ entry.title|upper }}</h1> {{ entry.body }}<br/> Published {{ entry.data|date:quot;d F Yquot; }}, <a href=”{{ entry.get_absolute_url }}”>link</a>. {% endfor %} </body> </html>
  • 21. Tag and Filter  Build in Filters and Tags  Custom tag and filter libraries Put logic in tags {% load comments %} <h1>{{ entry.title|upper }}</h1> {{ entry.body }}<br/> Published {{ entry.data|date:quot;d F Yquot; }}, <a href=”{{ entry.get_absolute_url }}”>link</a>. <h3>评论: </h3> {% get_comment_list for entry as comment_list %} {% for comment in comment_list %} {{ comment.content }} {% endfor %}
  • 22. Template Inheritance base.html index.html <html> <head> <title> {% extend “base.html” %} {% block title %} {% block title %} {% endblock %} Main page </title> {% endblock %} </head> {% block body %} <body> Content {% block body %} {% endblock %} {% endblock %} </body> </html>
  • 23. URL Dispatcher Brower Template URL Dispatcher View Model DataBase
  • 24. URL Dispatcher urlpatterns = patterns('', #http://jianghu.leyubox.com/articles/ ((r'^articles/$', ‘article.views.index'), ) #http://jianghu.leyubox.com/articles/2003/ (r'^articles/(?P<year>d{4})/$', ‘article.views.year_archive'), # http://jianghu.leyubox.com/articles/2003/ 12/ (r'^articles/(?P<year>d{4})/(?P<month>d{2})/$', 'article.views.month_archive'), # http://jianghu.leyubox.com/articles/2003/ 12/3 (r'^articles/(?P<year>d{4})/(?P<month>d{2})/(?P<day>d+)/$', 'article..views.article_detail'), )
  • 25. Outline  Overview  Architecture  Modules  Example  Links
  • 26. Modules  Form  Adminstration interface  Custom Middleware  Caching  Signals  Comments system  More...
  • 27. Modules:Form class ContactForm(forms.Form): subject = forms.CharField(max_length=100) message = forms.CharField(widget=forms.Textarea) sender = forms.EmailField() cc_myself = forms.BooleanField(required=False) <form action=quot;/contact/quot; method=quot;POSTquot;> {{ form.as_table}} <input type=quot;submitquot; value=quot;Submitquot; /> </form>
  • 29. Modules: Custom Middleware chain of processes request response Common Session Authentication Profile Middleware Middleware Middleware Middleware
  • 30. Modules: Caching Memcached Database Filesystem Local-memory Dummy BaseCache template caching Per-View Caching Per-Site Caching
  • 31. Modules:More...  Sessions  Authentication system  Internationalization and localization  Syndication feeds(RSS/Atom)  E-mail(sending)  Pagination  Signals
  • 32. Outline  Overview  Architecture  Modules  Example  Links
  • 33. Example  django_admin startproject leyubbs  modify setting.py  set database options  append admin app: django.contrib.admin  python manager.py syncdb  python manager.py runserver  modify urls.py, append /admin path
  • 34. Example(cont...)  python manager.py startapp article  add a model  python manager.py syncdb  explore admin page  inset a record in adminstration interface  add a veiw function  add a url
  • 35. Outline  Overview  Architecture  Modules  Example  Links
  • 37. Links: Resource  http://www.djangoproject.com/ For more information (Documentation,Download and News)  http://www.djangobook.com/ A Good book to learn Django  http://www.djangopluggables.com A lot of Django Pluggables available online Explore at  http://www.pinaxproject.com/ Community Development