SlideShare une entreprise Scribd logo
1  sur  40
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

AngularJS $http Interceptors (Explanation and Examples)
AngularJS $http Interceptors (Explanation and Examples)AngularJS $http Interceptors (Explanation and Examples)
AngularJS $http Interceptors (Explanation and Examples)Brian Swartzfager
 
How to implement internationalization (i18n) in angular application(multiple ...
How to implement internationalization (i18n) in angular application(multiple ...How to implement internationalization (i18n) in angular application(multiple ...
How to implement internationalization (i18n) in angular application(multiple ...Katy Slemon
 
Angular directives and pipes
Angular directives and pipesAngular directives and pipes
Angular directives and pipesKnoldus Inc.
 
Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2Knoldus Inc.
 
Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 formsEyal Vardi
 
Angular kickstart slideshare
Angular kickstart   slideshareAngular kickstart   slideshare
Angular kickstart slideshareSaleemMalik52
 
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
 
An Introduction to ReactJS
An Introduction to ReactJSAn Introduction to ReactJS
An Introduction to ReactJSAll Things Open
 
Clean VIP (Clean Swift) architecture
Clean VIP (Clean Swift) architectureClean VIP (Clean Swift) architecture
Clean VIP (Clean Swift) architectureJianbin LIN
 
Angular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesAngular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesWebStackAcademy
 
Python Templating Engine - Intro to Jinja
Python Templating Engine - Intro to JinjaPython Templating Engine - Intro to Jinja
Python Templating Engine - Intro to JinjaEueung Mulyana
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API07.pallav
 
React native development with expo
React native development with expoReact native development with expo
React native development with expoSangSun Park
 
Dependency injection in Java, from naive to functional
Dependency injection in Java, from naive to functionalDependency injection in Java, from naive to functional
Dependency injection in Java, from naive to functionalMarian Wamsiedel
 
Chromium에 contribution하기
Chromium에 contribution하기Chromium에 contribution하기
Chromium에 contribution하기규영 허
 
Angular 4 The new Http Client Module
Angular 4 The new Http Client ModuleAngular 4 The new Http Client Module
Angular 4 The new Http Client Modulearjun singh
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentationritika1
 

Tendances (20)

AngularJS $http Interceptors (Explanation and Examples)
AngularJS $http Interceptors (Explanation and Examples)AngularJS $http Interceptors (Explanation and Examples)
AngularJS $http Interceptors (Explanation and Examples)
 
Angular routing
Angular routingAngular routing
Angular routing
 
Angular js PPT
Angular js PPTAngular js PPT
Angular js PPT
 
How to implement internationalization (i18n) in angular application(multiple ...
How to implement internationalization (i18n) in angular application(multiple ...How to implement internationalization (i18n) in angular application(multiple ...
How to implement internationalization (i18n) in angular application(multiple ...
 
Angular directives and pipes
Angular directives and pipesAngular directives and pipes
Angular directives and pipes
 
Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2
 
Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 forms
 
Angular kickstart slideshare
Angular kickstart   slideshareAngular kickstart   slideshare
Angular kickstart slideshare
 
JavaScript: Events Handling
JavaScript: Events HandlingJavaScript: Events Handling
JavaScript: Events Handling
 
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.
 
An Introduction to ReactJS
An Introduction to ReactJSAn Introduction to ReactJS
An Introduction to ReactJS
 
Clean VIP (Clean Swift) architecture
Clean VIP (Clean Swift) architectureClean VIP (Clean Swift) architecture
Clean VIP (Clean Swift) architecture
 
Angular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesAngular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP Services
 
Python Templating Engine - Intro to Jinja
Python Templating Engine - Intro to JinjaPython Templating Engine - Intro to Jinja
Python Templating Engine - Intro to Jinja
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
 
React native development with expo
React native development with expoReact native development with expo
React native development with expo
 
Dependency injection in Java, from naive to functional
Dependency injection in Java, from naive to functionalDependency injection in Java, from naive to functional
Dependency injection in Java, from naive to functional
 
Chromium에 contribution하기
Chromium에 contribution하기Chromium에 contribution하기
Chromium에 contribution하기
 
Angular 4 The new Http Client Module
Angular 4 The new Http Client ModuleAngular 4 The new Http Client Module
Angular 4 The new Http Client Module
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentation
 

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

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

Dernier

How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...software pro Development
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...kalichargn70th171
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
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
 
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
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
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
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
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
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 
+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
 

Dernier (20)

How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
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
 
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...
 
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 🔝✔️✔️
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
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 🔝✔️✔️
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
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
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
+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...
 

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