SlideShare uma empresa Scribd logo
1 de 13
Class based views
   (django 1.3)
Reinout van Rees
• Nelen & Schuurmans
 • Django
 • Geo stuff, graphs, loads of python libs
 • Water management
• http://reinout.vanrees.org
• @reinoutvanrees
Great 1.3 feature: CBV
  (class based views)

• Models are classes, so why not views?
• Django 1.3+
• Bad PR: “class based generic views”
• Question: who uses generic views?
Classes and objects:
         theory

• “Encapsulation”: everything in one place
  instead of all over the place.
• “Inheritance”: inherit and change/add a
  couple of things. Helps with reuse and
  DRY.
Function based view
           example
def _expensive_calculation(request):
    # Calculate something and cache the result.
    return 'something'


def some_view(request):
    template = 'my_app/someview.html'
    data = _expensive_calculation(request)
    return render_to_response(
        template,
        {'data': data},
        context_instance=RequestContext(request))
Class based view
              example
class SomeView(TemplateView):
    template_name = 'my_app/someview.html'

   def _expensive_calculation(self):
       # Calculate something and cache the result.
       # You can use self.request!
       return 'something'

   def get_context_data(self, **kwargs):
       return {'data': self._expensive_calculation()}
Hooking up in urls.py
urlpatterns = patterns(
    ...
    url(r'^function_based_view/$',
        'my_app.views.some_view',
        name='function_based_view'),
    url(r'^class_based_view/$',
        my_app.views.SomeView.as_view(),
        name='class_based_view'),
    ...
Edit views
class ProcessFormView(View):
   """
   A mixin that processes a form on POST.
   """
   def get(self, request, *args, **kwargs):
       form_class = self.get_form_class()
       form = self.get_form(form_class)
       return self.render_to_response(
           self.get_context_data(form=form))

   def post(self, request, *args, **kwargs):
       form_class = self.get_form_class()
       form = self.get_form(form_class)
       if form.is_valid():
           return self.form_valid(form)
       else:
           return self.form_invalid(form)
Behind the scenes

• A whole lot of of “mixin classes”.
• A huge stack of ‘em.
• Quite numerous.
• Mixed together.
• Lots of places to look and debug.
Documentation

• Currently the code is a better source of
  documentation than the code.
• So look in django/views/generic/*.py
• Basic suggestion: find out how to use the
  one or two you use daily.
Example
• TemplateView (from base.py)
 • template_name
 • get_context_data()
• FormView (from edit.py)
 • template_name
 • form_class
 • success_url
Feature request

• No more hand-made context dict
• But an object
• Basically: {‘view’: self}
• => {{ view.number_of_kittens }}
Questions?
   (And a Dutch advertisement I’m sneaking in
        while you’re all asking questions)

• Wij bij Nelen & Schuurmans zoeken weer
  nieuwe collega’s :-)
• 40 m/v bedrijf, 9 django.
• Veel open source, pypi, sinds kort github.
• Hartje Utrecht. Vlak bij een ijskraam.
• Schiet me aan (of reinout@vanrees.org)

Mais conteúdo relacionado

Mais procurados

【前端Mvc】之豆瓣说实践
【前端Mvc】之豆瓣说实践【前端Mvc】之豆瓣说实践
【前端Mvc】之豆瓣说实践
taobao.com
 

Mais procurados (20)

Backbonejs for beginners
Backbonejs for beginnersBackbonejs for beginners
Backbonejs for beginners
 
Tips for writing Javascript for Drupal
Tips for writing Javascript for DrupalTips for writing Javascript for Drupal
Tips for writing Javascript for Drupal
 
Jquery fundamentals
Jquery fundamentalsJquery fundamentals
Jquery fundamentals
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
Any tutor
Any tutorAny tutor
Any tutor
 
【前端Mvc】之豆瓣说实践
【前端Mvc】之豆瓣说实践【前端Mvc】之豆瓣说实践
【前端Mvc】之豆瓣说实践
 
Javascript for the c# developer
Javascript for the c# developerJavascript for the c# developer
Javascript for the c# developer
 
Development Approach
Development ApproachDevelopment Approach
Development Approach
 
cake phptutorial
cake phptutorialcake phptutorial
cake phptutorial
 
Javascript Object Oriented Programming
Javascript Object Oriented ProgrammingJavascript Object Oriented Programming
Javascript Object Oriented Programming
 
Backbone
BackboneBackbone
Backbone
 
jQuery Presentation
jQuery PresentationjQuery Presentation
jQuery Presentation
 
Learning the basics of the Drupal API
Learning the basics of the Drupal APILearning the basics of the Drupal API
Learning the basics of the Drupal API
 
Week3
Week3Week3
Week3
 
Simpler Core Data with RubyMotion
Simpler Core Data with RubyMotionSimpler Core Data with RubyMotion
Simpler Core Data with RubyMotion
 
JQuery introduction
JQuery introductionJQuery introduction
JQuery introduction
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
PostgreSQL's Secret NoSQL Superpowers
PostgreSQL's Secret NoSQL SuperpowersPostgreSQL's Secret NoSQL Superpowers
PostgreSQL's Secret NoSQL Superpowers
 
ASP.NET MVC and Entity Framework 4
ASP.NET MVC and Entity Framework 4ASP.NET MVC and Entity Framework 4
ASP.NET MVC and Entity Framework 4
 
Jquery
JqueryJquery
Jquery
 

Semelhante a Django class based views (Dutch Django meeting presentation)

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
 
Backbone.js Simple Tutorial
Backbone.js Simple TutorialBackbone.js Simple Tutorial
Backbone.js Simple Tutorial
추근 문
 
Django introduction @ UGent
Django introduction @ UGentDjango introduction @ UGent
Django introduction @ UGent
kevinvw
 
Apache Cayenne for WO Devs
Apache Cayenne for WO DevsApache Cayenne for WO Devs
Apache Cayenne for WO Devs
WO Community
 
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
 

Semelhante a Django class based views (Dutch Django meeting presentation) (20)

Django design-patterns
Django design-patternsDjango design-patterns
Django design-patterns
 
Django Overview
Django OverviewDjango Overview
Django Overview
 
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
 
Migrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mindMigrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mind
 
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
 
Data Migrations in the App Engine Datastore
Data Migrations in the App Engine DatastoreData Migrations in the App Engine Datastore
Data Migrations in the App Engine Datastore
 
Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!
 
Backbone.js Simple Tutorial
Backbone.js Simple TutorialBackbone.js Simple Tutorial
Backbone.js Simple Tutorial
 
Django introduction @ UGent
Django introduction @ UGentDjango introduction @ UGent
Django introduction @ UGent
 
Django Pro ORM
Django Pro ORMDjango Pro ORM
Django Pro ORM
 
JS Essence
JS EssenceJS Essence
JS Essence
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
Introduction Django
Introduction DjangoIntroduction Django
Introduction Django
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
DJ-06-Views-Templates.pptx
DJ-06-Views-Templates.pptxDJ-06-Views-Templates.pptx
DJ-06-Views-Templates.pptx
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
What's new in the Drupal 7 API?
What's new in the Drupal 7 API?What's new in the Drupal 7 API?
What's new in the Drupal 7 API?
 
Apache Cayenne for WO Devs
Apache Cayenne for WO DevsApache Cayenne for WO Devs
Apache Cayenne for WO Devs
 
Staying Sane with Drupal NEPHP
Staying Sane with Drupal NEPHPStaying Sane with Drupal NEPHP
Staying Sane with Drupal NEPHP
 
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
 

Mais de Reinout van Rees

Practical project automation (PyGrunn conference)
Practical project automation (PyGrunn conference)Practical project automation (PyGrunn conference)
Practical project automation (PyGrunn conference)
Reinout van Rees
 

Mais de Reinout van Rees (13)

Practical project automation (PyGrunn conference)
Practical project automation (PyGrunn conference)Practical project automation (PyGrunn conference)
Practical project automation (PyGrunn conference)
 
Geographic information websites for water management.
Geographic information websites for water management.Geographic information websites for water management.
Geographic information websites for water management.
 
Practical project automation
Practical project automationPractical project automation
Practical project automation
 
Full econstruct end results overview
Full econstruct end results overviewFull econstruct end results overview
Full econstruct end results overview
 
bcxml taxonomy implementation screenshots
bcxml taxonomy implementation screenshotsbcxml taxonomy implementation screenshots
bcxml taxonomy implementation screenshots
 
EBEW2001 econstruct summary
EBEW2001 econstruct summaryEBEW2001 econstruct summary
EBEW2001 econstruct summary
 
Technical MSc background
Technical MSc backgroundTechnical MSc background
Technical MSc background
 
Semantic web, python, construction industry
Semantic web, python, construction industrySemantic web, python, construction industry
Semantic web, python, construction industry
 
econstruct summary
econstruct summaryeconstruct summary
econstruct summary
 
semantic web and construction industry
semantic web and construction industrysemantic web and construction industry
semantic web and construction industry
 
Semantic web and building specifications
Semantic web and building specificationsSemantic web and building specifications
Semantic web and building specifications
 
semantic web and construction industry
semantic web and construction industrysemantic web and construction industry
semantic web and construction industry
 
VR information frontend
VR information frontendVR information frontend
VR information frontend
 

Último

🔥HOT🔥📲9602870969🔥Prostitute Service in Udaipur Call Girls in City Palace Lake...
🔥HOT🔥📲9602870969🔥Prostitute Service in Udaipur Call Girls in City Palace Lake...🔥HOT🔥📲9602870969🔥Prostitute Service in Udaipur Call Girls in City Palace Lake...
🔥HOT🔥📲9602870969🔥Prostitute Service in Udaipur Call Girls in City Palace Lake...
Apsara Of India
 
💕📲09602870969💓Girl Escort Services Udaipur Call Girls in Chittorgarh Haldighati
💕📲09602870969💓Girl Escort Services Udaipur Call Girls in Chittorgarh Haldighati💕📲09602870969💓Girl Escort Services Udaipur Call Girls in Chittorgarh Haldighati
💕📲09602870969💓Girl Escort Services Udaipur Call Girls in Chittorgarh Haldighati
Apsara Of India
 
BERMUDA Triangle the mystery of life.pptx
BERMUDA Triangle the mystery of life.pptxBERMUDA Triangle the mystery of life.pptx
BERMUDA Triangle the mystery of life.pptx
seri bangash
 

Último (20)

🔥HOT🔥📲9602870969🔥Prostitute Service in Udaipur Call Girls in City Palace Lake...
🔥HOT🔥📲9602870969🔥Prostitute Service in Udaipur Call Girls in City Palace Lake...🔥HOT🔥📲9602870969🔥Prostitute Service in Udaipur Call Girls in City Palace Lake...
🔥HOT🔥📲9602870969🔥Prostitute Service in Udaipur Call Girls in City Palace Lake...
 
Top 10 Traditional Indian Handicrafts.pptx
Top 10 Traditional Indian Handicrafts.pptxTop 10 Traditional Indian Handicrafts.pptx
Top 10 Traditional Indian Handicrafts.pptx
 
Texas Tales Brenham and Amarillo Experiences Elevated by Find American Rental...
Texas Tales Brenham and Amarillo Experiences Elevated by Find American Rental...Texas Tales Brenham and Amarillo Experiences Elevated by Find American Rental...
Texas Tales Brenham and Amarillo Experiences Elevated by Find American Rental...
 
Call Girls Service !! Indirapuram!! @9999965857 Delhi 🫦 No Advance VVVIP 🍎 S...
Call Girls Service !! Indirapuram!! @9999965857 Delhi 🫦 No Advance  VVVIP 🍎 S...Call Girls Service !! Indirapuram!! @9999965857 Delhi 🫦 No Advance  VVVIP 🍎 S...
Call Girls Service !! Indirapuram!! @9999965857 Delhi 🫦 No Advance VVVIP 🍎 S...
 
visa consultant | 📞📞 03094429236 || Best Study Visa Consultant
visa consultant | 📞📞 03094429236 || Best Study Visa Consultantvisa consultant | 📞📞 03094429236 || Best Study Visa Consultant
visa consultant | 📞📞 03094429236 || Best Study Visa Consultant
 
Hire 💕 8617697112 Chamba Call Girls Service Call Girls Agency
Hire 💕 8617697112 Chamba Call Girls Service Call Girls AgencyHire 💕 8617697112 Chamba Call Girls Service Call Girls Agency
Hire 💕 8617697112 Chamba Call Girls Service Call Girls Agency
 
High Profile 🔝 8250077686 📞 Call Girls Service in Siri Fort🍑
High Profile 🔝 8250077686 📞 Call Girls Service in Siri Fort🍑High Profile 🔝 8250077686 📞 Call Girls Service in Siri Fort🍑
High Profile 🔝 8250077686 📞 Call Girls Service in Siri Fort🍑
 
Book Cheap Flight Tickets - TraveljunctionUK
Book  Cheap Flight Tickets - TraveljunctionUKBook  Cheap Flight Tickets - TraveljunctionUK
Book Cheap Flight Tickets - TraveljunctionUK
 
Discover Mathura And Vrindavan A Spritual Journey.pdf
Discover Mathura And Vrindavan A Spritual Journey.pdfDiscover Mathura And Vrindavan A Spritual Journey.pdf
Discover Mathura And Vrindavan A Spritual Journey.pdf
 
Hire 💕 8617697112 Reckong Peo Call Girls Service Call Girls Agency
Hire 💕 8617697112 Reckong Peo Call Girls Service Call Girls AgencyHire 💕 8617697112 Reckong Peo Call Girls Service Call Girls Agency
Hire 💕 8617697112 Reckong Peo Call Girls Service Call Girls Agency
 
08448380779 Call Girls In Shahdara Women Seeking Men
08448380779 Call Girls In Shahdara Women Seeking Men08448380779 Call Girls In Shahdara Women Seeking Men
08448380779 Call Girls In Shahdara Women Seeking Men
 
💕📲09602870969💓Girl Escort Services Udaipur Call Girls in Chittorgarh Haldighati
💕📲09602870969💓Girl Escort Services Udaipur Call Girls in Chittorgarh Haldighati💕📲09602870969💓Girl Escort Services Udaipur Call Girls in Chittorgarh Haldighati
💕📲09602870969💓Girl Escort Services Udaipur Call Girls in Chittorgarh Haldighati
 
9 Days Kenya Ultimate Safari Odyssey with Kibera Holiday Safaris
9 Days Kenya Ultimate Safari Odyssey with Kibera Holiday Safaris9 Days Kenya Ultimate Safari Odyssey with Kibera Holiday Safaris
9 Days Kenya Ultimate Safari Odyssey with Kibera Holiday Safaris
 
Hire 💕 8617697112 Champawat Call Girls Service Call Girls Agency
Hire 💕 8617697112 Champawat Call Girls Service Call Girls AgencyHire 💕 8617697112 Champawat Call Girls Service Call Girls Agency
Hire 💕 8617697112 Champawat Call Girls Service Call Girls Agency
 
08448380779 Call Girls In Chirag Enclave Women Seeking Men
08448380779 Call Girls In Chirag Enclave Women Seeking Men08448380779 Call Girls In Chirag Enclave Women Seeking Men
08448380779 Call Girls In Chirag Enclave Women Seeking Men
 
ITALY - Visa Options for expats and digital nomads
ITALY - Visa Options for expats and digital nomadsITALY - Visa Options for expats and digital nomads
ITALY - Visa Options for expats and digital nomads
 
BERMUDA Triangle the mystery of life.pptx
BERMUDA Triangle the mystery of life.pptxBERMUDA Triangle the mystery of life.pptx
BERMUDA Triangle the mystery of life.pptx
 
08448380779 Call Girls In Bhikaji Cama Palace Women Seeking Men
08448380779 Call Girls In Bhikaji Cama Palace Women Seeking Men08448380779 Call Girls In Bhikaji Cama Palace Women Seeking Men
08448380779 Call Girls In Bhikaji Cama Palace Women Seeking Men
 
Kanpur Call Girls Service ☎ ️82500–77686 ☎️ Enjoy 24/7 Escort Service
Kanpur Call Girls Service ☎ ️82500–77686 ☎️ Enjoy 24/7 Escort ServiceKanpur Call Girls Service ☎ ️82500–77686 ☎️ Enjoy 24/7 Escort Service
Kanpur Call Girls Service ☎ ️82500–77686 ☎️ Enjoy 24/7 Escort Service
 
A tour of African gastronomy - World Tourism Organization
A tour of African gastronomy - World Tourism OrganizationA tour of African gastronomy - World Tourism Organization
A tour of African gastronomy - World Tourism Organization
 

Django class based views (Dutch Django meeting presentation)

  • 1. Class based views (django 1.3)
  • 2. Reinout van Rees • Nelen & Schuurmans • Django • Geo stuff, graphs, loads of python libs • Water management • http://reinout.vanrees.org • @reinoutvanrees
  • 3. Great 1.3 feature: CBV (class based views) • Models are classes, so why not views? • Django 1.3+ • Bad PR: “class based generic views” • Question: who uses generic views?
  • 4. Classes and objects: theory • “Encapsulation”: everything in one place instead of all over the place. • “Inheritance”: inherit and change/add a couple of things. Helps with reuse and DRY.
  • 5. Function based view example def _expensive_calculation(request): # Calculate something and cache the result. return 'something' def some_view(request): template = 'my_app/someview.html' data = _expensive_calculation(request) return render_to_response( template, {'data': data}, context_instance=RequestContext(request))
  • 6. Class based view example class SomeView(TemplateView): template_name = 'my_app/someview.html' def _expensive_calculation(self): # Calculate something and cache the result. # You can use self.request! return 'something' def get_context_data(self, **kwargs): return {'data': self._expensive_calculation()}
  • 7. Hooking up in urls.py urlpatterns = patterns( ... url(r'^function_based_view/$', 'my_app.views.some_view', name='function_based_view'), url(r'^class_based_view/$', my_app.views.SomeView.as_view(), name='class_based_view'), ...
  • 8. Edit views class ProcessFormView(View): """ A mixin that processes a form on POST. """ def get(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) return self.render_to_response( self.get_context_data(form=form)) def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form)
  • 9. Behind the scenes • A whole lot of of “mixin classes”. • A huge stack of ‘em. • Quite numerous. • Mixed together. • Lots of places to look and debug.
  • 10. Documentation • Currently the code is a better source of documentation than the code. • So look in django/views/generic/*.py • Basic suggestion: find out how to use the one or two you use daily.
  • 11. Example • TemplateView (from base.py) • template_name • get_context_data() • FormView (from edit.py) • template_name • form_class • success_url
  • 12. Feature request • No more hand-made context dict • But an object • Basically: {‘view’: self} • => {{ view.number_of_kittens }}
  • 13. Questions? (And a Dutch advertisement I’m sneaking in while you’re all asking questions) • Wij bij Nelen & Schuurmans zoeken weer nieuwe collega’s :-) • 40 m/v bedrijf, 9 django. • Veel open source, pypi, sinds kort github. • Hartje Utrecht. Vlak bij een ijskraam. • Schiet me aan (of reinout@vanrees.org)

Notas do Editor

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n