SlideShare a Scribd company logo
1 of 40
Download to read offline
Best practices 
for 
Class-Based Views 
Two
 Scoops
 of
 Django
 -
 Chapter
 9 
@starwilly
Why Class-Based View
https://www.flickr.com/photos/kent-chen/8986036246 
DRY 
Don’t
 Repeat
 Yourself
Learning Curve
 Django
 Class-Based-View
 Inspector 
http://ccbv.co.uk/
Outline 
• Django View 
• Class-Based View (CBV) 
• Generic Class-based View (GCBV) 
• Detail View 
• General Tips for Django CBVs
Django View 
is simply a Python function that 
takes a Web request and returns a Web response. 
request View response
A Simple Function-Based View 
from django.http import HttpResponse 
def my_view(request): 
if request.method == 'GET': 
# view logic 
return HttpResponse('result') 
if request.method == 'POST': 
# view logic 
return HttpResponse('result')
Let’s Using 
Class-based View
Class-Based View 
django.views.generic.View 
FBV CBV 
def my_view(request): 
from django.views.generic import View 
class MyView(View):
request View response 
def my_view(request): 
… 
return HttpResponse(‘result’) 
from django.views.generic import View 
class MyView(View): 
request
 ? 
function
 ? 
response
 ? 
FBV CBV
django.views.generic.View
as_view() 
Returns a callable view 
that takes a request and returns a response
URLconf 
urlpatterns = patterns(‘', 
url(r'^$', ‘blog.views.homepage’), 
) 
from blog.views import HomepageView 
urlpatterns = patterns(‘', 
url(r'^$', HomepageView.as_view()), 
) 
FBV 
CBV
Dispatch HTTP Verbs 
from django.http import HttpResponse 
def my_view(request): 
if request.method == 'GET': 
# view logic 
return HttpResponse('result') 
if request.method == 'POST': 
# view logic 
return HttpResponse('result') 
from django.views.generic import View 
from django.http import HttpResponse 
class MyView(View): 
? 
?
dispatch() 
def dispatch(self, request, *args, **kwargs): 
# Try to dispatch to the right method; 
# if a method doesn't exist, defer to the error handler. 
# Also defer to the error handler if the 
# request method isn't on the approved list. 
if request.method.lower() in self.http_method_names: 
handler = getattr(self, request.method.lower(), self.http_method_not_allowed) 
else: 
handler = self.http_method_not_allowed 
return handler(request, *args, **kwargs)
From FBV to CBV 
FBV CBV 
from django.http import HttpResponse 
def my_view(request): 
if request.method == 'GET': 
# view logic 
return HttpResponse('result') 
if request.method == 'POST': 
# view logic 
return HttpResponse('result') 
from django.views.generic import View 
from django.http import HttpResponse 
class MyView(View): 
def get(self, request): 
# view logic 
return HttpResponse('result') 
def post(self, request): 
# view logic 
return HttpResponse('result')
Generic Class-based views 
(GCBVs) 
CreateView 
UpdateView 
DetailView 
DeleteView 
ListView 
TemplateView 
RedirectView
Display A Blog Post (FBV v.s. CBV) 
http://blog.mysite.com/post/12997/ 
FBV CBV 
def post_detail(request, pk): 
post = get_object_or_404(Post, pk=pk) 
return render(request, 
'post_detail.html', 
{'post’: post}) 
class PostDetailView(DetailView): 
model = Post
DetailView 
Attributes 
content_type = None 
context_object_name = None 
model = None 
pk_url_kwarg = ‘pk' 
queryset = None 
slug_field = ‘slug' 
slug_url_kwarg = ‘slug' 
template_name = None 
template_name_field = None 
template_name_suffix = ‘_detail' 
Method Flowchart 
1 dispatch() 
2 http_method_not_allowed() 
3 get_template_names() 
4 get_slug_field() 
5 get_queryset() 
6 get_object() 
7 get_context_object_name() 
8 get_context_data() 
9 get() 
10 render_to_response()
DetailView - get() 
def get(self, request, *args, **kwargs): 
self.object = self.get_object() 
context = self.get_context_data(object=self.object) 
return self.render_to_response(context) 
as_view() 
dispatch() 
get() 
get_object() 
render_to_response() get_context_data()
DetailView 
def post_detail(request, pk): 
post = get_object_or_404(Post, pk=pk) 
return render(request, ‘post_detail.html', {'post': post}) 
Method Flowchart 
1 dispatch() 
2 http_method_not_allowed() 
3 get_template_names() 
4 get_slug_field() 
5 get_queryset() 
6 get_object() 
7 get_context_object_name() 
8 get_context_data() 
9 get() 
10 render_to_response() 
render_to_response() 
get_object() 
get_context_data()
How do you customize 
CBVs behavior?
1. Attributes
class PostDetailView(DetailView): 
model = Post 
context_object_name = 'post_obj' 
template_name = 'post.html' 
h1{{ object.title }}/h1 
div 
{{ object.content }} 
/div 
h1{{ post.title }}/h1 
div 
{{ post.content }} 
/div 
h1{{ post_obj.title }}/h1 
div 
{{ post_obj.content }} 
/div 
post.html 
Customize - Attributes 
post_detail.html
2. Override methods
Customize - Overrides 
class PostDetailView(DetailView): 
model = Post 
def get_queryset(self): 
qs = super(PostDetail, self).get_queryset() 
return qs.published() 
def get_context_data(self, **kwargs): 
context = super(PostDetail, self).get_context_data(**kwargs) 
context[‘recommended_posts’] = (self.object. 
get_recommended_post(user=self.request.user)[:5]) 
return context

More Related Content

Similar to Ch9 .Best Practices for Class-Based Views

Django Class-based views (Slovenian)
Django Class-based views (Slovenian)Django Class-based views (Slovenian)
Django Class-based views (Slovenian)Luka Zakrajšek
 
tangowithdjango - Ch15
tangowithdjango - Ch15tangowithdjango - Ch15
tangowithdjango - Ch15Asika Kuo
 
Building complex User Interfaces with Sitecore and React
Building complex User Interfaces with Sitecore and ReactBuilding complex User Interfaces with Sitecore and React
Building complex User Interfaces with Sitecore and ReactJonne Kats
 
Introduction to backbone presentation
Introduction to backbone presentationIntroduction to backbone presentation
Introduction to backbone presentationBrian Hogg
 
Gutenberg sous le capot, modules réutilisables
Gutenberg sous le capot, modules réutilisablesGutenberg sous le capot, modules réutilisables
Gutenberg sous le capot, modules réutilisablesRiad Benguella
 
DJ-06-Views-Templates.pptx
DJ-06-Views-Templates.pptxDJ-06-Views-Templates.pptx
DJ-06-Views-Templates.pptxDamien Raczy
 
Django for Beginners
Django for BeginnersDjango for Beginners
Django for BeginnersJason Davies
 
Django class based views (Dutch Django meeting presentation)
Django class based views (Dutch Django meeting presentation)Django class based views (Dutch Django meeting presentation)
Django class based views (Dutch Django meeting presentation)Reinout van Rees
 
How to Mess Up Your Angular UI Components
How to Mess Up Your Angular UI ComponentsHow to Mess Up Your Angular UI Components
How to Mess Up Your Angular UI Componentscagataycivici
 
Django workshop : let's make a blog
Django workshop : let's make a blogDjango workshop : let's make a blog
Django workshop : let's make a blogPierre Sudron
 
Writing HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAEWriting HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAERon Reiter
 
Gae Meets Django
Gae Meets DjangoGae Meets Django
Gae Meets Djangofool2nd
 
PHPConf-TW 2012 # Twig
PHPConf-TW 2012 # TwigPHPConf-TW 2012 # Twig
PHPConf-TW 2012 # TwigWake Liu
 
Web осень 2012 лекция 6
Web осень 2012 лекция 6Web осень 2012 лекция 6
Web осень 2012 лекция 6Technopark
 
Backbone.js Simple Tutorial
Backbone.js Simple TutorialBackbone.js Simple Tutorial
Backbone.js Simple Tutorial추근 문
 
JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"GeeksLab Odessa
 
Web весна 2013 лекция 6
Web весна 2013 лекция 6Web весна 2013 лекция 6
Web весна 2013 лекция 6Technopark
 

Similar to Ch9 .Best Practices for Class-Based Views (20)

Django Bogotá. CBV
Django Bogotá. CBVDjango Bogotá. CBV
Django Bogotá. CBV
 
Django Class-based views (Slovenian)
Django Class-based views (Slovenian)Django Class-based views (Slovenian)
Django Class-based views (Slovenian)
 
Django
DjangoDjango
Django
 
tangowithdjango - Ch15
tangowithdjango - Ch15tangowithdjango - Ch15
tangowithdjango - Ch15
 
Building complex User Interfaces with Sitecore and React
Building complex User Interfaces with Sitecore and ReactBuilding complex User Interfaces with Sitecore and React
Building complex User Interfaces with Sitecore and React
 
Introduction to backbone presentation
Introduction to backbone presentationIntroduction to backbone presentation
Introduction to backbone presentation
 
Gutenberg sous le capot, modules réutilisables
Gutenberg sous le capot, modules réutilisablesGutenberg sous le capot, modules réutilisables
Gutenberg sous le capot, modules réutilisables
 
DJ-06-Views-Templates.pptx
DJ-06-Views-Templates.pptxDJ-06-Views-Templates.pptx
DJ-06-Views-Templates.pptx
 
Django for Beginners
Django for BeginnersDjango for Beginners
Django for Beginners
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
Django class based views (Dutch Django meeting presentation)
Django class based views (Dutch Django meeting presentation)Django class based views (Dutch Django meeting presentation)
Django class based views (Dutch Django meeting presentation)
 
How to Mess Up Your Angular UI Components
How to Mess Up Your Angular UI ComponentsHow to Mess Up Your Angular UI Components
How to Mess Up Your Angular UI Components
 
Django workshop : let's make a blog
Django workshop : let's make a blogDjango workshop : let's make a blog
Django workshop : let's make a blog
 
Writing HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAEWriting HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAE
 
Gae Meets Django
Gae Meets DjangoGae Meets Django
Gae Meets Django
 
PHPConf-TW 2012 # Twig
PHPConf-TW 2012 # TwigPHPConf-TW 2012 # Twig
PHPConf-TW 2012 # Twig
 
Web осень 2012 лекция 6
Web осень 2012 лекция 6Web осень 2012 лекция 6
Web осень 2012 лекция 6
 
Backbone.js Simple Tutorial
Backbone.js Simple TutorialBackbone.js Simple Tutorial
Backbone.js Simple Tutorial
 
JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"
 
Web весна 2013 лекция 6
Web весна 2013 лекция 6Web весна 2013 лекция 6
Web весна 2013 лекция 6
 

Recently uploaded

EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 

Recently uploaded (20)

EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 

Ch9 .Best Practices for Class-Based Views

  • 1. Best practices for Class-Based Views Two
  • 5.  -
  • 16. Outline • Django View • Class-Based View (CBV) • Generic Class-based View (GCBV) • Detail View • General Tips for Django CBVs
  • 17. Django View is simply a Python function that takes a Web request and returns a Web response. request View response
  • 18. A Simple Function-Based View from django.http import HttpResponse def my_view(request): if request.method == 'GET': # view logic return HttpResponse('result') if request.method == 'POST': # view logic return HttpResponse('result')
  • 20. Class-Based View django.views.generic.View FBV CBV def my_view(request): from django.views.generic import View class MyView(View):
  • 21. request View response def my_view(request): … return HttpResponse(‘result’) from django.views.generic import View class MyView(View): request
  • 26. as_view() Returns a callable view that takes a request and returns a response
  • 27. URLconf urlpatterns = patterns(‘', url(r'^$', ‘blog.views.homepage’), ) from blog.views import HomepageView urlpatterns = patterns(‘', url(r'^$', HomepageView.as_view()), ) FBV CBV
  • 28. Dispatch HTTP Verbs from django.http import HttpResponse def my_view(request): if request.method == 'GET': # view logic return HttpResponse('result') if request.method == 'POST': # view logic return HttpResponse('result') from django.views.generic import View from django.http import HttpResponse class MyView(View): ? ?
  • 29. dispatch() def dispatch(self, request, *args, **kwargs): # Try to dispatch to the right method; # if a method doesn't exist, defer to the error handler. # Also defer to the error handler if the # request method isn't on the approved list. if request.method.lower() in self.http_method_names: handler = getattr(self, request.method.lower(), self.http_method_not_allowed) else: handler = self.http_method_not_allowed return handler(request, *args, **kwargs)
  • 30. From FBV to CBV FBV CBV from django.http import HttpResponse def my_view(request): if request.method == 'GET': # view logic return HttpResponse('result') if request.method == 'POST': # view logic return HttpResponse('result') from django.views.generic import View from django.http import HttpResponse class MyView(View): def get(self, request): # view logic return HttpResponse('result') def post(self, request): # view logic return HttpResponse('result')
  • 31. Generic Class-based views (GCBVs) CreateView UpdateView DetailView DeleteView ListView TemplateView RedirectView
  • 32. Display A Blog Post (FBV v.s. CBV) http://blog.mysite.com/post/12997/ FBV CBV def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'post_detail.html', {'post’: post}) class PostDetailView(DetailView): model = Post
  • 33. DetailView Attributes content_type = None context_object_name = None model = None pk_url_kwarg = ‘pk' queryset = None slug_field = ‘slug' slug_url_kwarg = ‘slug' template_name = None template_name_field = None template_name_suffix = ‘_detail' Method Flowchart 1 dispatch() 2 http_method_not_allowed() 3 get_template_names() 4 get_slug_field() 5 get_queryset() 6 get_object() 7 get_context_object_name() 8 get_context_data() 9 get() 10 render_to_response()
  • 34. DetailView - get() def get(self, request, *args, **kwargs): self.object = self.get_object() context = self.get_context_data(object=self.object) return self.render_to_response(context) as_view() dispatch() get() get_object() render_to_response() get_context_data()
  • 35. DetailView def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, ‘post_detail.html', {'post': post}) Method Flowchart 1 dispatch() 2 http_method_not_allowed() 3 get_template_names() 4 get_slug_field() 5 get_queryset() 6 get_object() 7 get_context_object_name() 8 get_context_data() 9 get() 10 render_to_response() render_to_response() get_object() get_context_data()
  • 36. How do you customize CBVs behavior?
  • 38. class PostDetailView(DetailView): model = Post context_object_name = 'post_obj' template_name = 'post.html' h1{{ object.title }}/h1 div {{ object.content }} /div h1{{ post.title }}/h1 div {{ post.content }} /div h1{{ post_obj.title }}/h1 div {{ post_obj.content }} /div post.html Customize - Attributes post_detail.html
  • 40. Customize - Overrides class PostDetailView(DetailView): model = Post def get_queryset(self): qs = super(PostDetail, self).get_queryset() return qs.published() def get_context_data(self, **kwargs): context = super(PostDetail, self).get_context_data(**kwargs) context[‘recommended_posts’] = (self.object. get_recommended_post(user=self.request.user)[:5]) return context
  • 42. class SecretMessageMixin(object): def get_context_data(self,**kwargs):self).get_context_data(**kwargs) context[“secret_message] = ‘Hello’ return context class PostDetailView(SecretMessageMixin, DetailView): model = Post Customize - Mixins {% extends ‘base.html’ %} div Secret Message is {{ secret_message }} /div views.py post_detail.html
  • 43. Mixins 1. Mixins should inherit from Python’s built-in object type 2. Base view by Django always go to the right 3. Mixins go to the left of the base view class SecretMessageMixin(object): … class PostDetailView(SecretMessageMixin, DetailView): model = Post 1 3 2
  • 45. Tip1. Access Control from django.contrib.auth.decorators import login_required class LoginRequiredMixin(object): @classmethod def as_view(cls, **initkwargs): view = super(LoginRequiredMixin, cls).as_view(**initkwargs) return login_required(view) class PostDetail(LoginRequiredMixin, DetailView): model = Post
  • 46. MultiplePermissionsRequiredMixin LoginRequiredMixin PermissionRequiredMixin CsrfExemptMixin django-braces https://github.com/brack3t/django-braces FormValidMessageMixin SuccessURLRedirectListMixin FormInvalidMessageMixin SelectRelatedMixin JSONResponseMixin AjaxResponseMixin
  • 47. Tip2. Where should I put my code ? dispatch() get_context_data() form_valid() form_invalid() get_queryset() • Custom actions on every Http request • Add additional object to context • Custom Actions on Views with Valid Forms • Custom Actions on Views with Invalid Forms • Filter posts by query string
  • 48. Custom Actions on Views with Valid Forms form_valid() Custom Actions on Views with Invalid Forms form_invalid() from django.views.generic import CreateView from braces.views import LoginRequiredMixin from .models import Post class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ('title', ‘content') def form_invalid(self, form): # Do custom logic return super(PostCreateView, self).form_valid(form) def form_valid(self, form): # Do custom logic return super(PostCreateView, self).form_valid(form)
  • 49. Filter posts by query string get_queryset() from django.views.generic import ListView from .models import Post class PostListView(ListView): model = Post def get_queryset(self): queryset = super(PostListView, self).get_queryset() q = self.request.GET.get('q') if q: queryset = qs.filter(title__icontains=q) return queryset {# templates/blog/_post_search.html #} form action={% url “post-list %} method=GET input type=text name=q/ button type=submitSearch/ /form
  • 50. Tip3. Access url parameters http://blog.mysite.com/author/john/ url(r’^author/(?Pusernamew+)/$’, AuthorPostListView.as_view()) from django.views.generic import ListView from .models import Post class AuthorPostListView.as_view(ListView): model = Post paginate_by = 10 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs['author']) queryset = super(AuthorPostListView.as_view, self).get_queryset() return queryset.filter(author=user)
  • 51. Tip4. Using the View Object class PostMixin(object): @cached_property def likes_and_favorites(self): likes = self.objects.likes() favorites = self.objects.favorites() return { 'likes': likes, 'favorites': favorites, 'favorites_count': favorites.count(), } from django.utils.functional import cached_property from django.views.generic import UpdateView from .tasks import notify_users_who_favorited class PostUpdateView(PostMixin, UpdateView): model = Post fields = ('title', 'content') def form_valid(self, form): notify_users_who_favorited( instance=self.object, favorites = self.like_and_favorites['favorites'] )
  • 52. Tip4. Using the View Object call
  • 54.  template ContextMixin def get_context_data(self, **kwargs): if 'view' not in kwargs: kwargs['view'] = self return kwargs {% extends 'base.html' %} {% block likes_and_favorites %} ul liLikes: {{ view.likes_and_favorites.likes }}/li liFavorites: {{ view.likes_and_favorites.favorites_count}} /li /ul {% endblock likes_and_favorites %} class PostMixin(object): @cached_property def likes_and_favorites(self): likes = self.objects.likes() favorites = self.objects.favorites() return { 'likes': likes, 'favorites': favorites, 'favorites_count': favorites.count(), } How
  • 55.  it
  • 57.  ?
  • 58. Guidelines • Less view code is better • Never repeat code in views • Views should handle presentation logic • Keep your view simple • Use FBV for 403, 404, 500 error handlers • Keep your mixins simple
  • 59. Summary FBV v.s. CBV Generic Class-based View as_view() dispatch() Generic Class-based View Attribute Method Override Mixins LoginRequiredMixin Override Which Methods Access url parameters Using View Object Customize CBVs Behavior Tips for CBVs