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

What's hot

Spring boot
Spring bootSpring boot
Spring boot
Bhagwat Kumar
 
MVC ppt presentation
MVC ppt presentationMVC ppt presentation
MVC ppt presentation
Bhavin Shah
 
Spring Framework - Validation
Spring Framework - ValidationSpring Framework - Validation
Spring Framework - Validation
Dzmitry Naskou
 
Hands-On Java web passando por Servlets, JSP, JSTL, JDBC, Hibernate, DAO, MV...
Hands-On Java web passando por  Servlets, JSP, JSTL, JDBC, Hibernate, DAO, MV...Hands-On Java web passando por  Servlets, JSP, JSTL, JDBC, Hibernate, DAO, MV...
Hands-On Java web passando por Servlets, JSP, JSTL, JDBC, Hibernate, DAO, MV...
Mario Jorge Pereira
 
introduction to Vue.js 3
introduction to Vue.js 3 introduction to Vue.js 3
introduction to Vue.js 3
ArezooKmn
 
Spring Boot
Spring BootSpring Boot
Spring Boot
Pei-Tang Huang
 
Form認証で学ぶSpring Security入門
Form認証で学ぶSpring Security入門Form認証で学ぶSpring Security入門
Form認証で学ぶSpring Security入門
Ryosuke Uchitate
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
Dzmitry Naskou
 
The Point of Vue - Intro to Vue.js
The Point of Vue - Intro to Vue.jsThe Point of Vue - Intro to Vue.js
The Point of Vue - Intro to Vue.js
Holly Schinsky
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.
David Gómez García
 
Spring MVC 3.0 Framework
Spring MVC 3.0 FrameworkSpring MVC 3.0 Framework
Java 8 Lambda and Streams
Java 8 Lambda and StreamsJava 8 Lambda and Streams
Java 8 Lambda and Streams
Venkata Naga Ravi
 
jQuery
jQueryjQuery
MongoDB and Node.js
MongoDB and Node.jsMongoDB and Node.js
MongoDB and Node.js
Norberto Leite
 
AngularJS: an introduction
AngularJS: an introductionAngularJS: an introduction
AngularJS: an introduction
Luigi De Russis
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
Arulmurugan Rajaraman
 
Object Calisthenics Applied to PHP
Object Calisthenics Applied to PHPObject Calisthenics Applied to PHP
Object Calisthenics Applied to PHP
Guilherme Blanco
 
Introduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoCIntroduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoC
Funnelll
 
Nestjs MasterClass Slides
Nestjs MasterClass SlidesNestjs MasterClass Slides
Nestjs MasterClass Slides
Nir Kaufman
 

What's hot (20)

Spring boot
Spring bootSpring boot
Spring boot
 
Spring annotation
Spring annotationSpring annotation
Spring annotation
 
MVC ppt presentation
MVC ppt presentationMVC ppt presentation
MVC ppt presentation
 
Spring Framework - Validation
Spring Framework - ValidationSpring Framework - Validation
Spring Framework - Validation
 
Hands-On Java web passando por Servlets, JSP, JSTL, JDBC, Hibernate, DAO, MV...
Hands-On Java web passando por  Servlets, JSP, JSTL, JDBC, Hibernate, DAO, MV...Hands-On Java web passando por  Servlets, JSP, JSTL, JDBC, Hibernate, DAO, MV...
Hands-On Java web passando por Servlets, JSP, JSTL, JDBC, Hibernate, DAO, MV...
 
introduction to Vue.js 3
introduction to Vue.js 3 introduction to Vue.js 3
introduction to Vue.js 3
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Form認証で学ぶSpring Security入門
Form認証で学ぶSpring Security入門Form認証で学ぶSpring Security入門
Form認証で学ぶSpring Security入門
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 
The Point of Vue - Intro to Vue.js
The Point of Vue - Intro to Vue.jsThe Point of Vue - Intro to Vue.js
The Point of Vue - Intro to Vue.js
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.
 
Spring MVC 3.0 Framework
Spring MVC 3.0 FrameworkSpring MVC 3.0 Framework
Spring MVC 3.0 Framework
 
Java 8 Lambda and Streams
Java 8 Lambda and StreamsJava 8 Lambda and Streams
Java 8 Lambda and Streams
 
jQuery
jQueryjQuery
jQuery
 
MongoDB and Node.js
MongoDB and Node.jsMongoDB and Node.js
MongoDB and Node.js
 
AngularJS: an introduction
AngularJS: an introductionAngularJS: an introduction
AngularJS: an introduction
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
Object Calisthenics Applied to PHP
Object Calisthenics Applied to PHPObject Calisthenics Applied to PHP
Object Calisthenics Applied to PHP
 
Introduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoCIntroduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoC
 
Nestjs MasterClass Slides
Nestjs MasterClass SlidesNestjs MasterClass Slides
Nestjs MasterClass Slides
 

Similar to Ch9 .Best Practices for Class-Based Views

Django Bogotá. CBV
Django Bogotá. CBVDjango Bogotá. CBV
Django Bogotá. CBV
ctrl-alt-delete
 
Django Class-based views (Slovenian)
Django Class-based views (Slovenian)Django Class-based views (Slovenian)
Django Class-based views (Slovenian)Luka Zakrajšek
 
Django
DjangoDjango
Django
Kangjin Jun
 
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 React
Jonne Kats
 
Introduction to backbone presentation
Introduction to backbone presentationIntroduction to backbone presentation
Introduction to backbone presentation
Brian 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éutilisables
Riad Benguella
 
DJ-06-Views-Templates.pptx
DJ-06-Views-Templates.pptxDJ-06-Views-Templates.pptx
DJ-06-Views-Templates.pptx
Damien Raczy
 
Django for Beginners
Django for BeginnersDjango for Beginners
Django for Beginners
Jason Davies
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
Knoldus Inc.
 
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 Components
cagataycivici
 
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
Pierre 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 GAE
Ron 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 # Twig
Wake 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

Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 
Why React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdfWhy React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdf
ayushiqss
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
Tier1 app
 
De mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEDe mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FME
Jelle | Nordend
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
varshanayak241
 
Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024
Sharepoint Designs
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
Cyanic lab
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
Globus
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Hivelance Technology
 
Visitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.appVisitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.app
NaapbooksPrivateLimi
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 

Recently uploaded (20)

Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 
Why React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdfWhy React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdf
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
De mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEDe mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FME
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
 
Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
 
Visitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.appVisitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.app
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.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