SlideShare a Scribd company logo
1 of 13
Download to read offline
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 beginnersDivakar Gu
 
Tips for writing Javascript for Drupal
Tips for writing Javascript for DrupalTips for writing Javascript for Drupal
Tips for writing Javascript for DrupalSergey 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# developerSalvatore Fazio
 
Development Approach
Development ApproachDevelopment Approach
Development Approachalexkingorg
 
cake phptutorial
cake phptutorialcake phptutorial
cake phptutorialice27
 
Javascript Object Oriented Programming
Javascript Object Oriented ProgrammingJavascript Object Oriented Programming
Javascript Object Oriented ProgrammingBunlong Van
 
jQuery Presentation
jQuery PresentationjQuery Presentation
jQuery PresentationRod 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 APIAlexandru Badiu
 
Simpler Core Data with RubyMotion
Simpler Core Data with RubyMotionSimpler Core Data with RubyMotion
Simpler Core Data with RubyMotionStefan Haflidason
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQueryZeeshan Khan
 
PostgreSQL's Secret NoSQL Superpowers
PostgreSQL's Secret NoSQL SuperpowersPostgreSQL's Secret NoSQL Superpowers
PostgreSQL's Secret NoSQL SuperpowersAmanda 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 4James Johnson
 

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 OverviewBrian Tol
 
Migrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mindMigrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mindValentine 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 DatastoreRyan 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 DjangoJoaquim Rocha
 
Introduction Django
Introduction DjangoIntroduction Django
Introduction DjangoWade Austin
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Djangocolinkingswood
 
DJ-06-Views-Templates.pptx
DJ-06-Views-Templates.pptxDJ-06-Views-Templates.pptx
DJ-06-Views-Templates.pptxDamien Raczy
 
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 NEPHPOscar 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 automationReinout van Rees
 
Full econstruct end results overview
Full econstruct end results overviewFull econstruct end results overview
Full econstruct end results overviewReinout van Rees
 
bcxml taxonomy implementation screenshots
bcxml taxonomy implementation screenshotsbcxml taxonomy implementation screenshots
bcxml taxonomy implementation screenshotsReinout van Rees
 
EBEW2001 econstruct summary
EBEW2001 econstruct summaryEBEW2001 econstruct summary
EBEW2001 econstruct summaryReinout van Rees
 
Semantic web, python, construction industry
Semantic web, python, construction industrySemantic web, python, construction industry
Semantic web, python, construction industryReinout van Rees
 
semantic web and construction industry
semantic web and construction industrysemantic web and construction industry
semantic web and construction industryReinout van Rees
 
Semantic web and building specifications
Semantic web and building specificationsSemantic web and building specifications
Semantic web and building specificationsReinout van Rees
 
semantic web and construction industry
semantic web and construction industrysemantic web and construction industry
semantic web and construction industryReinout 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

Da Nang Tourist Attractions, VN (越南 峴港旅遊景點).ppsx
Da Nang Tourist Attractions, VN (越南 峴港旅遊景點).ppsxDa Nang Tourist Attractions, VN (越南 峴港旅遊景點).ppsx
Da Nang Tourist Attractions, VN (越南 峴港旅遊景點).ppsxChung Yen Chang
 
A Presentation of Braga. It was made by students of school
A Presentation of Braga. It was made by students of schoolA Presentation of Braga. It was made by students of school
A Presentation of Braga. It was made by students of schoolApostolos Syropoulos
 
Culture and Identity through English as a Lingua Franca (1).pdf
Culture and Identity through English as a Lingua Franca (1).pdfCulture and Identity through English as a Lingua Franca (1).pdf
Culture and Identity through English as a Lingua Franca (1).pdfseijibrown2
 
TOURIST & ITS TYPE &MOTIVETIONAL FACTORS & BEHAVIOR .pptx
TOURIST & ITS TYPE &MOTIVETIONAL  FACTORS & BEHAVIOR .pptxTOURIST & ITS TYPE &MOTIVETIONAL  FACTORS & BEHAVIOR .pptx
TOURIST & ITS TYPE &MOTIVETIONAL FACTORS & BEHAVIOR .pptxkittustudy7
 
2024 Annual Meeting: Visit Portland, Maine
2024 Annual Meeting: Visit Portland, Maine2024 Annual Meeting: Visit Portland, Maine
2024 Annual Meeting: Visit Portland, MaineVisit Portland
 
The West Coast Trail Presentation for SAIT international students
The West Coast Trail Presentation for SAIT international studentsThe West Coast Trail Presentation for SAIT international students
The West Coast Trail Presentation for SAIT international studentsseijibrown2
 
Culture and Identity through English as a Lingua Franca.pdf
Culture and Identity through English as a Lingua Franca.pdfCulture and Identity through English as a Lingua Franca.pdf
Culture and Identity through English as a Lingua Franca.pdfseijibrown2
 
Exploring Uncharted Waters Your Guide To Private Sunset Cruise On Maui
Exploring Uncharted Waters Your Guide To Private Sunset Cruise On MauiExploring Uncharted Waters Your Guide To Private Sunset Cruise On Maui
Exploring Uncharted Waters Your Guide To Private Sunset Cruise On MauiMakena Coast Charters
 
pics from luxembourg exchange program 2016
pics from luxembourg exchange program 2016pics from luxembourg exchange program 2016
pics from luxembourg exchange program 2016seijibrown2
 
What Are The Best Locations In Aruba For A Thrilling Kayak Adventure
What Are The Best Locations In Aruba For A Thrilling Kayak AdventureWhat Are The Best Locations In Aruba For A Thrilling Kayak Adventure
What Are The Best Locations In Aruba For A Thrilling Kayak AdventureDelphi Watersports
 
Nanbokucho-period, Historical Origins of Modern Japan
Nanbokucho-period, Historical Origins of Modern JapanNanbokucho-period, Historical Origins of Modern Japan
Nanbokucho-period, Historical Origins of Modern Japanseijibrown2
 
Vietnam presentation for intercultural communications class
Vietnam presentation for intercultural communications classVietnam presentation for intercultural communications class
Vietnam presentation for intercultural communications classseijibrown2
 
How To Prepare For An Unforgettable Blackwater Dive In Kona
How To Prepare For An Unforgettable Blackwater Dive In KonaHow To Prepare For An Unforgettable Blackwater Dive In Kona
How To Prepare For An Unforgettable Blackwater Dive In KonaKona Ocean Adventures
 
Reflective Essay.pdf for Global Compentency
Reflective Essay.pdf for Global CompentencyReflective Essay.pdf for Global Compentency
Reflective Essay.pdf for Global Compentencyseijibrown2
 
Reflective Essay for global competency certificate
Reflective Essay for global competency certificateReflective Essay for global competency certificate
Reflective Essay for global competency certificateseijibrown2
 
My presentation on vietnam for Intercultural Communications
My presentation on vietnam for Intercultural CommunicationsMy presentation on vietnam for Intercultural Communications
My presentation on vietnam for Intercultural Communicationsseijibrown2
 
Traveling by Train in Sicily: A New Era of Comfort and Convenience
Traveling by Train in Sicily: A New Era of Comfort and ConvenienceTraveling by Train in Sicily: A New Era of Comfort and Convenience
Traveling by Train in Sicily: A New Era of Comfort and ConvenienceTime for Sicily
 

Recently uploaded (17)

Da Nang Tourist Attractions, VN (越南 峴港旅遊景點).ppsx
Da Nang Tourist Attractions, VN (越南 峴港旅遊景點).ppsxDa Nang Tourist Attractions, VN (越南 峴港旅遊景點).ppsx
Da Nang Tourist Attractions, VN (越南 峴港旅遊景點).ppsx
 
A Presentation of Braga. It was made by students of school
A Presentation of Braga. It was made by students of schoolA Presentation of Braga. It was made by students of school
A Presentation of Braga. It was made by students of school
 
Culture and Identity through English as a Lingua Franca (1).pdf
Culture and Identity through English as a Lingua Franca (1).pdfCulture and Identity through English as a Lingua Franca (1).pdf
Culture and Identity through English as a Lingua Franca (1).pdf
 
TOURIST & ITS TYPE &MOTIVETIONAL FACTORS & BEHAVIOR .pptx
TOURIST & ITS TYPE &MOTIVETIONAL  FACTORS & BEHAVIOR .pptxTOURIST & ITS TYPE &MOTIVETIONAL  FACTORS & BEHAVIOR .pptx
TOURIST & ITS TYPE &MOTIVETIONAL FACTORS & BEHAVIOR .pptx
 
2024 Annual Meeting: Visit Portland, Maine
2024 Annual Meeting: Visit Portland, Maine2024 Annual Meeting: Visit Portland, Maine
2024 Annual Meeting: Visit Portland, Maine
 
The West Coast Trail Presentation for SAIT international students
The West Coast Trail Presentation for SAIT international studentsThe West Coast Trail Presentation for SAIT international students
The West Coast Trail Presentation for SAIT international students
 
Culture and Identity through English as a Lingua Franca.pdf
Culture and Identity through English as a Lingua Franca.pdfCulture and Identity through English as a Lingua Franca.pdf
Culture and Identity through English as a Lingua Franca.pdf
 
Exploring Uncharted Waters Your Guide To Private Sunset Cruise On Maui
Exploring Uncharted Waters Your Guide To Private Sunset Cruise On MauiExploring Uncharted Waters Your Guide To Private Sunset Cruise On Maui
Exploring Uncharted Waters Your Guide To Private Sunset Cruise On Maui
 
pics from luxembourg exchange program 2016
pics from luxembourg exchange program 2016pics from luxembourg exchange program 2016
pics from luxembourg exchange program 2016
 
What Are The Best Locations In Aruba For A Thrilling Kayak Adventure
What Are The Best Locations In Aruba For A Thrilling Kayak AdventureWhat Are The Best Locations In Aruba For A Thrilling Kayak Adventure
What Are The Best Locations In Aruba For A Thrilling Kayak Adventure
 
Nanbokucho-period, Historical Origins of Modern Japan
Nanbokucho-period, Historical Origins of Modern JapanNanbokucho-period, Historical Origins of Modern Japan
Nanbokucho-period, Historical Origins of Modern Japan
 
Vietnam presentation for intercultural communications class
Vietnam presentation for intercultural communications classVietnam presentation for intercultural communications class
Vietnam presentation for intercultural communications class
 
How To Prepare For An Unforgettable Blackwater Dive In Kona
How To Prepare For An Unforgettable Blackwater Dive In KonaHow To Prepare For An Unforgettable Blackwater Dive In Kona
How To Prepare For An Unforgettable Blackwater Dive In Kona
 
Reflective Essay.pdf for Global Compentency
Reflective Essay.pdf for Global CompentencyReflective Essay.pdf for Global Compentency
Reflective Essay.pdf for Global Compentency
 
Reflective Essay for global competency certificate
Reflective Essay for global competency certificateReflective Essay for global competency certificate
Reflective Essay for global competency certificate
 
My presentation on vietnam for Intercultural Communications
My presentation on vietnam for Intercultural CommunicationsMy presentation on vietnam for Intercultural Communications
My presentation on vietnam for Intercultural Communications
 
Traveling by Train in Sicily: A New Era of Comfort and Convenience
Traveling by Train in Sicily: A New Era of Comfort and ConvenienceTraveling by Train in Sicily: A New Era of Comfort and Convenience
Traveling by Train in Sicily: A New Era of Comfort and Convenience
 

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