SlideShare a Scribd company logo
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)

More Related Content

What's hot

Backbonejs for beginners
Backbonejs for beginnersBackbonejs for beginners
Backbonejs for beginners
Divakar Gu
 
Tips for writing Javascript for Drupal
Tips for writing Javascript for DrupalTips for writing Javascript for Drupal
Tips for writing Javascript for Drupal
Sergey Semashko
 
【前端Mvc】之豆瓣说实践
【前端Mvc】之豆瓣说实践【前端Mvc】之豆瓣说实践
【前端Mvc】之豆瓣说实践taobao.com
 
Javascript for the c# developer
Javascript for the c# developerJavascript for the c# developer
Javascript for the c# developer
Salvatore Fazio
 
Development Approach
Development ApproachDevelopment Approach
Development Approach
alexkingorg
 
cake phptutorial
cake phptutorialcake phptutorial
cake phptutorial
ice27
 
Javascript Object Oriented Programming
Javascript Object Oriented ProgrammingJavascript Object Oriented Programming
Javascript Object Oriented Programming
Bunlong Van
 
Backbone
BackboneBackbone
Backbone
Glenn De Backer
 
jQuery Presentation
jQuery PresentationjQuery Presentation
jQuery Presentation
Rod Johnson
 
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
Alexandru Badiu
 
Simpler Core Data with RubyMotion
Simpler Core Data with RubyMotionSimpler Core Data with RubyMotion
Simpler Core Data with RubyMotion
Stefan Haflidason
 
JQuery introduction
JQuery introductionJQuery introduction
JQuery introduction
NexThoughts Technologies
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
Zeeshan Khan
 
PostgreSQL's Secret NoSQL Superpowers
PostgreSQL's Secret NoSQL SuperpowersPostgreSQL's Secret NoSQL Superpowers
PostgreSQL's Secret NoSQL Superpowers
Amanda Gilmore
 
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
James Johnson
 
Jquery
JqueryJquery
Jquery
Pushkar Dutt
 

What's hot (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
 

Similar to Django class based views (Dutch Django meeting presentation)

Django Overview
Django OverviewDjango Overview
Django Overview
Brian Tol
 
Migrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mindMigrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mind
Valentine Matsveiko
 
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
LEDC 2016
 
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 EngineYared Ayalew
 
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
Ryan Morlok
 
Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!
Doris Chen
 
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 @ UGentkevinvw
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
Joaquim Rocha
 
Introduction Django
Introduction DjangoIntroduction Django
Introduction Django
Wade Austin
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
colinkingswood
 
DJ-06-Views-Templates.pptx
DJ-06-Views-Templates.pptxDJ-06-Views-Templates.pptx
DJ-06-Views-Templates.pptx
Damien Raczy
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
Jussi Pohjolainen
 
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?
Alexandru Badiu
 
Apache Cayenne for WO Devs
Apache Cayenne for WO DevsApache Cayenne for WO Devs
Apache Cayenne for WO DevsWO Community
 
Staying Sane with Drupal NEPHP
Staying Sane with Drupal NEPHPStaying Sane with Drupal NEPHP
Staying Sane with Drupal NEPHP
Oscar Merida
 
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 FrameworkRicardo Soares
 

Similar to 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
 
Migrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mindMigrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mind
 
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
 
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
 

More from 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
 
Geographic information websites for water management.
Geographic information websites for water management.Geographic information websites for water management.
Geographic information websites for water management.
Reinout van Rees
 
Practical project automation
Practical project automationPractical project automation
Practical project automation
Reinout van Rees
 
Full econstruct end results overview
Full econstruct end results overviewFull econstruct end results overview
Full econstruct end results overview
Reinout van Rees
 
bcxml taxonomy implementation screenshots
bcxml taxonomy implementation screenshotsbcxml taxonomy implementation screenshots
bcxml taxonomy implementation screenshots
Reinout van Rees
 
EBEW2001 econstruct summary
EBEW2001 econstruct summaryEBEW2001 econstruct summary
EBEW2001 econstruct summary
Reinout van Rees
 
Technical MSc background
Technical MSc backgroundTechnical MSc background
Technical MSc background
Reinout van Rees
 
Semantic web, python, construction industry
Semantic web, python, construction industrySemantic web, python, construction industry
Semantic web, python, construction industry
Reinout van Rees
 
econstruct summary
econstruct summaryeconstruct summary
econstruct summary
Reinout van Rees
 
semantic web and construction industry
semantic web and construction industrysemantic web and construction industry
semantic web and construction industry
Reinout van Rees
 
Semantic web and building specifications
Semantic web and building specificationsSemantic web and building specifications
Semantic web and building specifications
Reinout van Rees
 
semantic web and construction industry
semantic web and construction industrysemantic web and construction industry
semantic web and construction industry
Reinout van Rees
 
VR information frontend
VR information frontendVR information frontend
VR information frontend
Reinout van Rees
 

More from 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
 

Recently uploaded

Hidden Gems of Europe - DISCOVERING THE CONTINENT'S BEST-KEPT SECRETS
Hidden Gems of Europe - DISCOVERING THE CONTINENT'S BEST-KEPT SECRETSHidden Gems of Europe - DISCOVERING THE CONTINENT'S BEST-KEPT SECRETS
Hidden Gems of Europe - DISCOVERING THE CONTINENT'S BEST-KEPT SECRETS
Kamil Uğraş TÜRKOĞLU
 
Agence Régionale du Tourisme Grand Est - brochure MICE 2024.pdf
Agence Régionale du Tourisme Grand Est - brochure MICE 2024.pdfAgence Régionale du Tourisme Grand Est - brochure MICE 2024.pdf
Agence Régionale du Tourisme Grand Est - brochure MICE 2024.pdf
MICEboard
 
欧洲杯开户-信誉的欧洲杯开户-正规欧洲杯开户|【​网址​🎉ac123.net🎉​】
欧洲杯开户-信誉的欧洲杯开户-正规欧洲杯开户|【​网址​🎉ac123.net🎉​】欧洲杯开户-信誉的欧洲杯开户-正规欧洲杯开户|【​网址​🎉ac123.net🎉​】
欧洲杯开户-信誉的欧洲杯开户-正规欧洲杯开户|【​网址​🎉ac123.net🎉​】
bljeremy734
 
Winter Festivities in Italy
Winter Festivities in ItalyWinter Festivities in Italy
Winter Festivities in Italy
Time for Sicily
 
Antarctica- Icy wilderness of extremes and wonder
Antarctica- Icy wilderness of extremes and wonderAntarctica- Icy wilderness of extremes and wonder
Antarctica- Icy wilderness of extremes and wonder
tahreemzahra82
 
LUXURY TRAVEL THE ULTIMATE TOKYO EXPERIENCE FROM SINGAPORE.pdf
LUXURY TRAVEL THE ULTIMATE TOKYO EXPERIENCE FROM SINGAPORE.pdfLUXURY TRAVEL THE ULTIMATE TOKYO EXPERIENCE FROM SINGAPORE.pdf
LUXURY TRAVEL THE ULTIMATE TOKYO EXPERIENCE FROM SINGAPORE.pdf
Diper Tour
 
Understanding the Running Costs of Electric Scooters.pptx
Understanding the Running Costs of Electric Scooters.pptxUnderstanding the Running Costs of Electric Scooters.pptx
Understanding the Running Costs of Electric Scooters.pptx
Zivah ElectriVa Private Limited
 
Ooty Honeymoon Package from Chennai.docx
Ooty Honeymoon Package from Chennai.docxOoty Honeymoon Package from Chennai.docx
Ooty Honeymoon Package from Chennai.docx
Ooty Heritage Tours and Travels
 
4 DAYS MASAI MARA WILDEBEEST MIGRATION SAFARI TOUR PACKAGE KENYA
4 DAYS MASAI MARA WILDEBEEST MIGRATION SAFARI TOUR PACKAGE KENYA4 DAYS MASAI MARA WILDEBEEST MIGRATION SAFARI TOUR PACKAGE KENYA
4 DAYS MASAI MARA WILDEBEEST MIGRATION SAFARI TOUR PACKAGE KENYA
Bush Troop Safari
 
How To Talk To a Live Person at American Airlines
How To Talk To a Live Person at American AirlinesHow To Talk To a Live Person at American Airlines
How To Talk To a Live Person at American Airlines
flyn goo
 
Jose RIZAL History and his travel Paris to berlin
Jose RIZAL History and his travel Paris to berlinJose RIZAL History and his travel Paris to berlin
Jose RIZAL History and his travel Paris to berlin
MaryGraceArdalesLope
 
Uk Visa Complete Guide and application process
Uk Visa Complete Guide and application processUk Visa Complete Guide and application process
Uk Visa Complete Guide and application process
pandeypratikwgblindi
 
TOP 10 Historic Places To See in Kuruskhetra.
TOP 10 Historic Places To See in Kuruskhetra.TOP 10 Historic Places To See in Kuruskhetra.
TOP 10 Historic Places To See in Kuruskhetra.
ujjwalsethi113
 
The Power of a Glamping Go-To-Market Accelerator Plan.pptx
The Power of a Glamping Go-To-Market Accelerator Plan.pptxThe Power of a Glamping Go-To-Market Accelerator Plan.pptx
The Power of a Glamping Go-To-Market Accelerator Plan.pptx
RezStream
 

Recently uploaded (14)

Hidden Gems of Europe - DISCOVERING THE CONTINENT'S BEST-KEPT SECRETS
Hidden Gems of Europe - DISCOVERING THE CONTINENT'S BEST-KEPT SECRETSHidden Gems of Europe - DISCOVERING THE CONTINENT'S BEST-KEPT SECRETS
Hidden Gems of Europe - DISCOVERING THE CONTINENT'S BEST-KEPT SECRETS
 
Agence Régionale du Tourisme Grand Est - brochure MICE 2024.pdf
Agence Régionale du Tourisme Grand Est - brochure MICE 2024.pdfAgence Régionale du Tourisme Grand Est - brochure MICE 2024.pdf
Agence Régionale du Tourisme Grand Est - brochure MICE 2024.pdf
 
欧洲杯开户-信誉的欧洲杯开户-正规欧洲杯开户|【​网址​🎉ac123.net🎉​】
欧洲杯开户-信誉的欧洲杯开户-正规欧洲杯开户|【​网址​🎉ac123.net🎉​】欧洲杯开户-信誉的欧洲杯开户-正规欧洲杯开户|【​网址​🎉ac123.net🎉​】
欧洲杯开户-信誉的欧洲杯开户-正规欧洲杯开户|【​网址​🎉ac123.net🎉​】
 
Winter Festivities in Italy
Winter Festivities in ItalyWinter Festivities in Italy
Winter Festivities in Italy
 
Antarctica- Icy wilderness of extremes and wonder
Antarctica- Icy wilderness of extremes and wonderAntarctica- Icy wilderness of extremes and wonder
Antarctica- Icy wilderness of extremes and wonder
 
LUXURY TRAVEL THE ULTIMATE TOKYO EXPERIENCE FROM SINGAPORE.pdf
LUXURY TRAVEL THE ULTIMATE TOKYO EXPERIENCE FROM SINGAPORE.pdfLUXURY TRAVEL THE ULTIMATE TOKYO EXPERIENCE FROM SINGAPORE.pdf
LUXURY TRAVEL THE ULTIMATE TOKYO EXPERIENCE FROM SINGAPORE.pdf
 
Understanding the Running Costs of Electric Scooters.pptx
Understanding the Running Costs of Electric Scooters.pptxUnderstanding the Running Costs of Electric Scooters.pptx
Understanding the Running Costs of Electric Scooters.pptx
 
Ooty Honeymoon Package from Chennai.docx
Ooty Honeymoon Package from Chennai.docxOoty Honeymoon Package from Chennai.docx
Ooty Honeymoon Package from Chennai.docx
 
4 DAYS MASAI MARA WILDEBEEST MIGRATION SAFARI TOUR PACKAGE KENYA
4 DAYS MASAI MARA WILDEBEEST MIGRATION SAFARI TOUR PACKAGE KENYA4 DAYS MASAI MARA WILDEBEEST MIGRATION SAFARI TOUR PACKAGE KENYA
4 DAYS MASAI MARA WILDEBEEST MIGRATION SAFARI TOUR PACKAGE KENYA
 
How To Talk To a Live Person at American Airlines
How To Talk To a Live Person at American AirlinesHow To Talk To a Live Person at American Airlines
How To Talk To a Live Person at American Airlines
 
Jose RIZAL History and his travel Paris to berlin
Jose RIZAL History and his travel Paris to berlinJose RIZAL History and his travel Paris to berlin
Jose RIZAL History and his travel Paris to berlin
 
Uk Visa Complete Guide and application process
Uk Visa Complete Guide and application processUk Visa Complete Guide and application process
Uk Visa Complete Guide and application process
 
TOP 10 Historic Places To See in Kuruskhetra.
TOP 10 Historic Places To See in Kuruskhetra.TOP 10 Historic Places To See in Kuruskhetra.
TOP 10 Historic Places To See in Kuruskhetra.
 
The Power of a Glamping Go-To-Market Accelerator Plan.pptx
The Power of a Glamping Go-To-Market Accelerator Plan.pptxThe Power of a Glamping Go-To-Market Accelerator Plan.pptx
The Power of a Glamping Go-To-Market Accelerator Plan.pptx
 

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)

Editor's Notes

  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