SlideShare une entreprise Scribd logo
1  sur  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)

Contenu connexe

Tendances

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

Tendances (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
 

Similaire à 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
 

Similaire à 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
 

Plus 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
 

Plus 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
 

Dernier

💕📲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
 
IATA GEOGRAPHY AREAS in the world, HM111
IATA GEOGRAPHY AREAS in the world, HM111IATA GEOGRAPHY AREAS in the world, HM111
IATA GEOGRAPHY AREAS in the world, HM111
2022472524
 
Ahmedabad Escort Service Ahmedabad Call Girl 0000000000
Ahmedabad Escort Service Ahmedabad Call Girl 0000000000Ahmedabad Escort Service Ahmedabad Call Girl 0000000000
Ahmedabad Escort Service Ahmedabad Call Girl 0000000000
mountabuangels4u
 
Vadodara Escort💋 Call Girl (Bindu) Service #Vadodara Call Girl @Independent G...
Vadodara Escort💋 Call Girl (Bindu) Service #Vadodara Call Girl @Independent G...Vadodara Escort💋 Call Girl (Bindu) Service #Vadodara Call Girl @Independent G...
Vadodara Escort💋 Call Girl (Bindu) Service #Vadodara Call Girl @Independent G...
mountabuangels4u
 
sample sample sample sample sample sample
sample sample sample sample sample samplesample sample sample sample sample sample
sample sample sample sample sample sample
Casey Keith
 

Dernier (20)

Kolkata Call Girls - 📞 8617697112 🔝 Top Class Call Girls Service Available
Kolkata Call Girls - 📞 8617697112 🔝 Top Class Call Girls Service AvailableKolkata Call Girls - 📞 8617697112 🔝 Top Class Call Girls Service Available
Kolkata Call Girls - 📞 8617697112 🔝 Top Class Call Girls Service Available
 
Siliguri Call Girls 8250077686 Service Offer VIP Hot Model
Siliguri Call Girls 8250077686 Service Offer VIP Hot ModelSiliguri Call Girls 8250077686 Service Offer VIP Hot Model
Siliguri Call Girls 8250077686 Service Offer VIP Hot Model
 
💕📲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
 
Genuine 8250077686 Hot and Beautiful 💕 Visakhapatnam Escorts call Girls
Genuine 8250077686 Hot and Beautiful 💕 Visakhapatnam Escorts call GirlsGenuine 8250077686 Hot and Beautiful 💕 Visakhapatnam Escorts call Girls
Genuine 8250077686 Hot and Beautiful 💕 Visakhapatnam Escorts call Girls
 
Hire 8617697112 Call Girls Udhampur For an Amazing Night
Hire 8617697112 Call Girls Udhampur For an Amazing NightHire 8617697112 Call Girls Udhampur For an Amazing Night
Hire 8617697112 Call Girls Udhampur For an Amazing Night
 
WhatsApp Chat: 📞 8617697112 Suri Call Girls available for hotel room package
WhatsApp Chat: 📞 8617697112 Suri Call Girls available for hotel room packageWhatsApp Chat: 📞 8617697112 Suri Call Girls available for hotel room package
WhatsApp Chat: 📞 8617697112 Suri Call Girls available for hotel room package
 
IATA GEOGRAPHY AREAS in the world, HM111
IATA GEOGRAPHY AREAS in the world, HM111IATA GEOGRAPHY AREAS in the world, HM111
IATA GEOGRAPHY AREAS in the world, HM111
 
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
 
Andheri Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Andheri Call Girls 🥰 8617370543 Service Offer VIP Hot ModelAndheri Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Andheri Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
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
 
Ahmedabad Escort Service Ahmedabad Call Girl 0000000000
Ahmedabad Escort Service Ahmedabad Call Girl 0000000000Ahmedabad Escort Service Ahmedabad Call Girl 0000000000
Ahmedabad Escort Service Ahmedabad Call Girl 0000000000
 
Ooty Call Girls 8250077686 Service Offer VIP Hot Model
Ooty Call Girls 8250077686 Service Offer VIP Hot ModelOoty Call Girls 8250077686 Service Offer VIP Hot Model
Ooty Call Girls 8250077686 Service Offer VIP Hot Model
 
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🍑
 
Alipore Call Girls - 📞 8617697112 🔝 Top Class Call Girls Service Available
Alipore Call Girls - 📞 8617697112 🔝 Top Class Call Girls Service AvailableAlipore Call Girls - 📞 8617697112 🔝 Top Class Call Girls Service Available
Alipore Call Girls - 📞 8617697112 🔝 Top Class Call Girls Service Available
 
WhatsApp Chat: 📞 8617697112 Independent Call Girls in Darjeeling
WhatsApp Chat: 📞 8617697112 Independent Call Girls in DarjeelingWhatsApp Chat: 📞 8617697112 Independent Call Girls in Darjeeling
WhatsApp Chat: 📞 8617697112 Independent Call Girls in Darjeeling
 
Ooty call girls 📞 8617697112 At Low Cost Cash Payment Booking
Ooty call girls 📞 8617697112 At Low Cost Cash Payment BookingOoty call girls 📞 8617697112 At Low Cost Cash Payment Booking
Ooty call girls 📞 8617697112 At Low Cost Cash Payment Booking
 
Vadodara Escort💋 Call Girl (Bindu) Service #Vadodara Call Girl @Independent G...
Vadodara Escort💋 Call Girl (Bindu) Service #Vadodara Call Girl @Independent G...Vadodara Escort💋 Call Girl (Bindu) Service #Vadodara Call Girl @Independent G...
Vadodara Escort💋 Call Girl (Bindu) Service #Vadodara Call Girl @Independent G...
 
Genuine 9332606886 Hot and Beautiful 💕 Pune Escorts call Girls
Genuine 9332606886 Hot and Beautiful 💕 Pune Escorts call GirlsGenuine 9332606886 Hot and Beautiful 💕 Pune Escorts call Girls
Genuine 9332606886 Hot and Beautiful 💕 Pune Escorts call Girls
 
sample sample sample sample sample sample
sample sample sample sample sample samplesample sample sample sample sample sample
sample sample sample sample sample sample
 
Night 7k to 12k Lahaul and Spiti Call Girls 👉👉 8617697112⭐⭐ 100% Genuine Esco...
Night 7k to 12k Lahaul and Spiti Call Girls 👉👉 8617697112⭐⭐ 100% Genuine Esco...Night 7k to 12k Lahaul and Spiti Call Girls 👉👉 8617697112⭐⭐ 100% Genuine Esco...
Night 7k to 12k Lahaul and Spiti Call Girls 👉👉 8617697112⭐⭐ 100% Genuine Esco...
 

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)

Notes de l'éditeur

  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