SlideShare una empresa de Scribd logo
1 de 40
Descargar para leer sin conexión
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

Más contenido relacionado

Similar a 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 a 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
 

Último

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 

Último (20)

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 

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