SlideShare ist ein Scribd-Unternehmen logo
1 von 40
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

FIWARE Wednesday Webinars - Integrating FIWARE with Blockchain/DLTs
FIWARE Wednesday Webinars - Integrating FIWARE with Blockchain/DLTsFIWARE Wednesday Webinars - Integrating FIWARE with Blockchain/DLTs
FIWARE Wednesday Webinars - Integrating FIWARE with Blockchain/DLTsFIWARE
 
JCR, Sling or AEM? Which API should I use and when?
JCR, Sling or AEM? Which API should I use and when?JCR, Sling or AEM? Which API should I use and when?
JCR, Sling or AEM? Which API should I use and when?connectwebex
 
Extending DSpace 7: DSpace-CRIS and DSpace-GLAM for empowered repositories an...
Extending DSpace 7: DSpace-CRIS and DSpace-GLAM for empowered repositories an...Extending DSpace 7: DSpace-CRIS and DSpace-GLAM for empowered repositories an...
Extending DSpace 7: DSpace-CRIS and DSpace-GLAM for empowered repositories an...4Science
 
FIWARE Global Summit - NGSI-LD – an Evolution from NGSIv2
FIWARE Global Summit - NGSI-LD – an Evolution from NGSIv2FIWARE Global Summit - NGSI-LD – an Evolution from NGSIv2
FIWARE Global Summit - NGSI-LD – an Evolution from NGSIv2FIWARE
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web APIhabib_786
 
Connect2016 AD1387 Integrate with XPages and Java
Connect2016 AD1387 Integrate with XPages and JavaConnect2016 AD1387 Integrate with XPages and Java
Connect2016 AD1387 Integrate with XPages and JavaJulian Robichaux
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design PatternsLilia Sfaxi
 
Understanding REST
Understanding RESTUnderstanding REST
Understanding RESTNitin Pande
 
SK Telecom - 망관리 프로젝트 TANGO의 오픈소스 데이터베이스 전환 여정 - 발표자 : 박승전, Project Manager, ...
SK Telecom - 망관리 프로젝트 TANGO의 오픈소스 데이터베이스 전환 여정 - 발표자 : 박승전, Project Manager, ...SK Telecom - 망관리 프로젝트 TANGO의 오픈소스 데이터베이스 전환 여정 - 발표자 : 박승전, Project Manager, ...
SK Telecom - 망관리 프로젝트 TANGO의 오픈소스 데이터베이스 전환 여정 - 발표자 : 박승전, Project Manager, ...Amazon Web Services Korea
 
Testcontainers - Geekout EE 2017 presentation
Testcontainers - Geekout EE 2017 presentationTestcontainers - Geekout EE 2017 presentation
Testcontainers - Geekout EE 2017 presentationRichard North
 
AWSKRUG-33번째-세션1.pdf
AWSKRUG-33번째-세션1.pdfAWSKRUG-33번째-세션1.pdf
AWSKRUG-33번째-세션1.pdfSeoyulYoon
 
Introduction to Smart Data Models
Introduction to Smart Data ModelsIntroduction to Smart Data Models
Introduction to Smart Data ModelsFIWARE
 
Asp.Net Core MVC , Razor page , Entity Framework Core
Asp.Net Core MVC , Razor page , Entity Framework CoreAsp.Net Core MVC , Razor page , Entity Framework Core
Asp.Net Core MVC , Razor page , Entity Framework Coremohamed elshafey
 
Terraform을 이용한 Infrastructure as Code 실전 구성하기 :: 변정훈::AWS Summit Seoul 2018
 Terraform을 이용한 Infrastructure as Code 실전 구성하기 :: 변정훈::AWS Summit Seoul 2018 Terraform을 이용한 Infrastructure as Code 실전 구성하기 :: 변정훈::AWS Summit Seoul 2018
Terraform을 이용한 Infrastructure as Code 실전 구성하기 :: 변정훈::AWS Summit Seoul 2018Amazon Web Services Korea
 
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptxUnit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptxMalla Reddy University
 
Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action Alex Movila
 
클라우드 네이티브 전환 요소 및 성공적인 쿠버네티스 도입 전략
클라우드 네이티브 전환 요소 및 성공적인 쿠버네티스 도입 전략클라우드 네이티브 전환 요소 및 성공적인 쿠버네티스 도입 전략
클라우드 네이티브 전환 요소 및 성공적인 쿠버네티스 도입 전략Open Source Consulting
 

Was ist angesagt? (20)

FIWARE Wednesday Webinars - Integrating FIWARE with Blockchain/DLTs
FIWARE Wednesday Webinars - Integrating FIWARE with Blockchain/DLTsFIWARE Wednesday Webinars - Integrating FIWARE with Blockchain/DLTs
FIWARE Wednesday Webinars - Integrating FIWARE with Blockchain/DLTs
 
JCR, Sling or AEM? Which API should I use and when?
JCR, Sling or AEM? Which API should I use and when?JCR, Sling or AEM? Which API should I use and when?
JCR, Sling or AEM? Which API should I use and when?
 
Extending DSpace 7: DSpace-CRIS and DSpace-GLAM for empowered repositories an...
Extending DSpace 7: DSpace-CRIS and DSpace-GLAM for empowered repositories an...Extending DSpace 7: DSpace-CRIS and DSpace-GLAM for empowered repositories an...
Extending DSpace 7: DSpace-CRIS and DSpace-GLAM for empowered repositories an...
 
FIWARE Global Summit - NGSI-LD – an Evolution from NGSIv2
FIWARE Global Summit - NGSI-LD – an Evolution from NGSIv2FIWARE Global Summit - NGSI-LD – an Evolution from NGSIv2
FIWARE Global Summit - NGSI-LD – an Evolution from NGSIv2
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Connect2016 AD1387 Integrate with XPages and Java
Connect2016 AD1387 Integrate with XPages and JavaConnect2016 AD1387 Integrate with XPages and Java
Connect2016 AD1387 Integrate with XPages and Java
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Understanding REST
Understanding RESTUnderstanding REST
Understanding REST
 
SK Telecom - 망관리 프로젝트 TANGO의 오픈소스 데이터베이스 전환 여정 - 발표자 : 박승전, Project Manager, ...
SK Telecom - 망관리 프로젝트 TANGO의 오픈소스 데이터베이스 전환 여정 - 발표자 : 박승전, Project Manager, ...SK Telecom - 망관리 프로젝트 TANGO의 오픈소스 데이터베이스 전환 여정 - 발표자 : 박승전, Project Manager, ...
SK Telecom - 망관리 프로젝트 TANGO의 오픈소스 데이터베이스 전환 여정 - 발표자 : 박승전, Project Manager, ...
 
Testcontainers - Geekout EE 2017 presentation
Testcontainers - Geekout EE 2017 presentationTestcontainers - Geekout EE 2017 presentation
Testcontainers - Geekout EE 2017 presentation
 
AWSKRUG-33번째-세션1.pdf
AWSKRUG-33번째-세션1.pdfAWSKRUG-33번째-세션1.pdf
AWSKRUG-33번째-세션1.pdf
 
Introduction to Smart Data Models
Introduction to Smart Data ModelsIntroduction to Smart Data Models
Introduction to Smart Data Models
 
Asp.Net Core MVC , Razor page , Entity Framework Core
Asp.Net Core MVC , Razor page , Entity Framework CoreAsp.Net Core MVC , Razor page , Entity Framework Core
Asp.Net Core MVC , Razor page , Entity Framework Core
 
Terraform을 이용한 Infrastructure as Code 실전 구성하기 :: 변정훈::AWS Summit Seoul 2018
 Terraform을 이용한 Infrastructure as Code 실전 구성하기 :: 변정훈::AWS Summit Seoul 2018 Terraform을 이용한 Infrastructure as Code 실전 구성하기 :: 변정훈::AWS Summit Seoul 2018
Terraform을 이용한 Infrastructure as Code 실전 구성하기 :: 변정훈::AWS Summit Seoul 2018
 
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptxUnit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
 
Nuxtjs cheat-sheet
Nuxtjs cheat-sheetNuxtjs cheat-sheet
Nuxtjs cheat-sheet
 
Spring boot jpa
Spring boot jpaSpring boot jpa
Spring boot jpa
 
Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action
 
클라우드 네이티브 전환 요소 및 성공적인 쿠버네티스 도입 전략
클라우드 네이티브 전환 요소 및 성공적인 쿠버네티스 도입 전략클라우드 네이티브 전환 요소 및 성공적인 쿠버네티스 도입 전략
클라우드 네이티브 전환 요소 및 성공적인 쿠버네티스 도입 전략
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Kürzlich hochgeladen

GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jGraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jNeo4j
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITmanoharjgpsolutions
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsJean Silva
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogueitservices996
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolsosttopstonverter
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingShane Coughlan
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonApplitools
 
Copilot para Microsoft 365 y Power Platform Copilot
Copilot para Microsoft 365 y Power Platform CopilotCopilot para Microsoft 365 y Power Platform Copilot
Copilot para Microsoft 365 y Power Platform CopilotEdgard Alejos
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...OnePlan Solutions
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slidesvaideheekore1
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shardsChristopher Curtin
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptxVinzoCenzo
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfRTS corp
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdfPros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdfkalichargn70th171
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...Bert Jan Schrijver
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?Alexandre Beguel
 

Kürzlich hochgeladen (20)

GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jGraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh IT
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero results
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogue
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration tools
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
 
Copilot para Microsoft 365 y Power Platform Copilot
Copilot para Microsoft 365 y Power Platform CopilotCopilot para Microsoft 365 y Power Platform Copilot
Copilot para Microsoft 365 y Power Platform Copilot
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slides
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptx
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdfPros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?
 

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