SlideShare uma empresa Scribd logo
1 de 31
Baixar para ler offline
Django Design Patterns 
Arun Ravindran
About Me 
Arun Ravindran 
Blogs and screencasts at arunrocks.com
Outline 
●Why Design Patterns? 
●Does Django follow MVC pattern? 
●Model Patterns 
●View Patterns 
●Template Patterns 
●Gyaan on Applying Patterns
“ 
A design pattern is a general reusable solution to a commonly occurring problem within a given context in software design
●Pattern are often elegant and beautiful code 
●Repeatable solutions 
●Gives a Common Lingo 
●Reduces Trial and Error 
●Formalizes best practices, say - 
○Don’t Repeat Yourself 
○Separation of Concerns 
○SOLID
 
Why Design Patterns?
Django and Patterns 
GoF Pattern 
Django Component 
Explanation 
Observer pattern 
Signals 
When one object changes state, all its listeners are notified and updated automatically 
Template Method 
Class based generic views 
Steps of an algorithm can be redefined by subclassing without changing the algorithm’s structure 
Fowler Pattern 
Django Component 
Explanation 
Active Record 
Django Models 
Encapsulates the database access, and adds domain logic on that data 
Identity Field 
Id Field 
Saves a database ID field in an object to maintain identity 
Template View 
Django Templates 
Renders into HTML by embedding markers in HTML
Does Django follow MVC? 
●MVC is easily misunderstood 
●Creators of Django prefer the term MTV 
●In reality, Django is an MVC variant 
●Compared to classic MVC – 
●“Model” is comparable to Django’s Models, 
●“View” is usually Django’s Templates 
●“Controller” is the entire framework itself
Model Patterns 
●Pattern: User Profiles 
●Pattern: Service Objects 
●Pattern: Custom Model Managers
User Profiles
User Profiles (contd.) 
1.Define the profile model 
2.Listen for User model’s post_save signal
User Profiles (contd.) 
3.Mention your app’s AppConfig 
4.Import signals in the AppConfig’s ready 
5.(Optional) Inline the User model’s admin
User Profiles (contd.) 
Usage: 
UserProfile.objects.get_or_create(user=u)
Service Objects 
●The adage “Fat Models, Thin Views” can lead to frighteningly obese models. 
●Service Objects are POPOs that encapsulate a ‘service’ or interactions with a system. 
●They are usually kept in a separate file named services.py 
●Common use cases: Interactions with external services, Helper tasks, Long- running tasks
Service Objects (contd.) 
1.Your model delegates to service objects 
2.Services are specialized classes:
Custom Model Managers
Custom Model Managers (contd.) 
1.Use custom manager for common queries 
2.Add it to your model
View Patterns 
●Pattern: Context Enhancers 
●Pattern: Access Controlled Views
Detour: What is a Mixin? 
‱Mixin is a class used to add properties and methods to other classes 
‱Composition or Inheritance? Sort of both. 
TemplateView 
View 
ContextMixin 
Template 
ResponseMixin
Context Enhancers 
●Several views might need the same queryset or values in context 
●Overriding get_context_data everywhere isn’t DRY 
●Instead, use a view mixin:
Access Controlled Views
Access Controlled Views (contd.) 
1.By using a decorator on a function based view or a class based view 
2.Or, by overriding the dispatch method through a mixin
Template Patterns 
●Pattern: Template Inheritance Tree 
●Pattern: Active Link
Template Inheritance Tree
Template Inheritance Tree (contd.) 
1.Build a base structure, with placeholders 
2.Similar pages are extended from base
Active Link
Active Link (contd.) 
Here is a simple template-only approach: 
1.Every template has the following line 
2.The snippet in _navbar.html will be: 
Custom tags can also be used
And the list goes on...
Gyaan on Patterns 
●How not to use patterns: 
oDon’t blindly apply. Explain why. 
oDon’t apply a pattern if you language supports a direct solution 
oDon’t try to retro-fit everything in terms of patterns 
oDon’t be afraid to create new patterns.
PATTERNS ARE EVERYWHERE
Thank you!
Image Credits 
‱http://fooyoh.com/geekapolis_gadgets_wishlist/657945 
‱http://www.bigalspets.ca/multi-stage- canister-filter-c-360.html 
‱https://wrapbootstrap.com/theme/sanoor- navbar-WB037R7G3 
‱Monty Python and the Holy Grail 
‱Warner Bros

Mais conteĂșdo relacionado

Mais procurados

AngularJS: Overview & Key Features
AngularJS: Overview & Key FeaturesAngularJS: Overview & Key Features
AngularJS: Overview & Key FeaturesMohamad Al Asmar
 
Factory Method Design Pattern
Factory Method Design PatternFactory Method Design Pattern
Factory Method Design Patternmelbournepatterns
 
AngularJS introduction
AngularJS introductionAngularJS introduction
AngularJS introductionTania Gonzales
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics PresentationShrinath Shenoy
 
Django Framework Overview forNon-Python Developers
Django Framework Overview forNon-Python DevelopersDjango Framework Overview forNon-Python Developers
Django Framework Overview forNon-Python DevelopersRosario Renga
 
Intro To Mvc Development In Php
Intro To Mvc Development In PhpIntro To Mvc Development In Php
Intro To Mvc Development In Phpfunkatron
 
Nicolas Embleton, Advanced Angular JS
Nicolas Embleton, Advanced Angular JSNicolas Embleton, Advanced Angular JS
Nicolas Embleton, Advanced Angular JSJavaScript Meetup HCMC
 
Angular Js Get Started - Complete Course
Angular Js Get Started - Complete CourseAngular Js Get Started - Complete Course
Angular Js Get Started - Complete CourseEPAM Systems
 
Web application development with Django framework
Web application development with Django frameworkWeb application development with Django framework
Web application development with Django frameworkflapiello
 
Making Django and NoSQL Play Nice
Making Django and NoSQL Play NiceMaking Django and NoSQL Play Nice
Making Django and NoSQL Play NiceAlex Gaynor
 
AngularJS application architecture
AngularJS application architectureAngularJS application architecture
AngularJS application architectureGabriele Falace
 
(An Extended) Beginners Guide to Object Orientation in PHP
(An Extended) Beginners Guide to Object Orientation in PHP(An Extended) Beginners Guide to Object Orientation in PHP
(An Extended) Beginners Guide to Object Orientation in PHPRick Ogden
 
Understanding angular js
Understanding angular jsUnderstanding angular js
Understanding angular jsAayush Shrestha
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Djangocolinkingswood
 
AngularJs presentation
AngularJs presentation AngularJs presentation
AngularJs presentation Phan Tuan
 
Front end development with Angular JS
Front end development with Angular JSFront end development with Angular JS
Front end development with Angular JSBipin
 

Mais procurados (20)

Extjs
ExtjsExtjs
Extjs
 
AngularJS: Overview & Key Features
AngularJS: Overview & Key FeaturesAngularJS: Overview & Key Features
AngularJS: Overview & Key Features
 
5 angularjs features
5 angularjs features5 angularjs features
5 angularjs features
 
Factory Method Design Pattern
Factory Method Design PatternFactory Method Design Pattern
Factory Method Design Pattern
 
AngularJS introduction
AngularJS introductionAngularJS introduction
AngularJS introduction
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics Presentation
 
Django Framework Overview forNon-Python Developers
Django Framework Overview forNon-Python DevelopersDjango Framework Overview forNon-Python Developers
Django Framework Overview forNon-Python Developers
 
Intro To Mvc Development In Php
Intro To Mvc Development In PhpIntro To Mvc Development In Php
Intro To Mvc Development In Php
 
Nicolas Embleton, Advanced Angular JS
Nicolas Embleton, Advanced Angular JSNicolas Embleton, Advanced Angular JS
Nicolas Embleton, Advanced Angular JS
 
Angular Js Get Started - Complete Course
Angular Js Get Started - Complete CourseAngular Js Get Started - Complete Course
Angular Js Get Started - Complete Course
 
Web application development with Django framework
Web application development with Django frameworkWeb application development with Django framework
Web application development with Django framework
 
Making Django and NoSQL Play Nice
Making Django and NoSQL Play NiceMaking Django and NoSQL Play Nice
Making Django and NoSQL Play Nice
 
AngularJS application architecture
AngularJS application architectureAngularJS application architecture
AngularJS application architecture
 
(An Extended) Beginners Guide to Object Orientation in PHP
(An Extended) Beginners Guide to Object Orientation in PHP(An Extended) Beginners Guide to Object Orientation in PHP
(An Extended) Beginners Guide to Object Orientation in PHP
 
Factory method pattern
Factory method patternFactory method pattern
Factory method pattern
 
Understanding angular js
Understanding angular jsUnderstanding angular js
Understanding angular js
 
Struts2
Struts2Struts2
Struts2
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
AngularJs presentation
AngularJs presentation AngularJs presentation
AngularJs presentation
 
Front end development with Angular JS
Front end development with Angular JSFront end development with Angular JS
Front end development with Angular JS
 

Semelhante a Django Patterns - Pycon India 2014

Design pattern in android
Design pattern in androidDesign pattern in android
Design pattern in androidJay Kumarr
 
Design patterns
Design patternsDesign patterns
Design patternsmudabbirwarsi
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to DjangoKnoldus Inc.
 
Introduction to django framework
Introduction to django frameworkIntroduction to django framework
Introduction to django frameworkKnoldus Inc.
 
Design Patterns every Android developer should know
Design Patterns every Android developer should knowDesign Patterns every Android developer should know
Design Patterns every Android developer should knowmuratcanbur
 
Design patterns in android
Design patterns in androidDesign patterns in android
Design patterns in androidZahra Heydari
 
Dependency injection using Google guice
Dependency injection using Google guiceDependency injection using Google guice
Dependency injection using Google guiceAman Verma
 
Design Patterns Part1
Design Patterns  Part1Design Patterns  Part1
Design Patterns Part1Tom Chen
 
Introduction To Design Patterns
Introduction To Design PatternsIntroduction To Design Patterns
Introduction To Design Patternssukumarraju6
 
Benefits of using software design patterns and when to use design pattern
Benefits of using software design patterns and when to use design patternBenefits of using software design patterns and when to use design pattern
Benefits of using software design patterns and when to use design patternBeroza Paul
 
Object Oriented, Design patterns and data modelling worshop
Object Oriented, Design patterns and data modelling worshopObject Oriented, Design patterns and data modelling worshop
Object Oriented, Design patterns and data modelling worshopMohammad Shawahneh
 
Introduction to django
Introduction to djangoIntroduction to django
Introduction to djangoVlad Voskoboynik
 
Gof design pattern
Gof design patternGof design pattern
Gof design patternnaveen kumar
 
Mixing Diagram, Tree, Text, Table and Form editors to build a kick-ass modeli...
Mixing Diagram, Tree, Text, Table and Form editors to build a kick-ass modeli...Mixing Diagram, Tree, Text, Table and Form editors to build a kick-ass modeli...
Mixing Diagram, Tree, Text, Table and Form editors to build a kick-ass modeli...Chauvin Mariot
 
Foster - Getting started with Angular
Foster - Getting started with AngularFoster - Getting started with Angular
Foster - Getting started with AngularMukundSonaiya1
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxanguraju1
 

Semelhante a Django Patterns - Pycon India 2014 (20)

Design pattern in android
Design pattern in androidDesign pattern in android
Design pattern in android
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
Introduction to django framework
Introduction to django frameworkIntroduction to django framework
Introduction to django framework
 
Design Patterns every Android developer should know
Design Patterns every Android developer should knowDesign Patterns every Android developer should know
Design Patterns every Android developer should know
 
Design patterns in android
Design patterns in androidDesign patterns in android
Design patterns in android
 
Dependency injection using Google guice
Dependency injection using Google guiceDependency injection using Google guice
Dependency injection using Google guice
 
JavaFX in Action Part I
JavaFX in Action Part IJavaFX in Action Part I
JavaFX in Action Part I
 
Design Patterns Part1
Design Patterns  Part1Design Patterns  Part1
Design Patterns Part1
 
Introduction To Design Patterns
Introduction To Design PatternsIntroduction To Design Patterns
Introduction To Design Patterns
 
Benefits of using software design patterns and when to use design pattern
Benefits of using software design patterns and when to use design patternBenefits of using software design patterns and when to use design pattern
Benefits of using software design patterns and when to use design pattern
 
Object Oriented, Design patterns and data modelling worshop
Object Oriented, Design patterns and data modelling worshopObject Oriented, Design patterns and data modelling worshop
Object Oriented, Design patterns and data modelling worshop
 
Introduction to django
Introduction to djangoIntroduction to django
Introduction to django
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Gof design pattern
Gof design patternGof design pattern
Gof design pattern
 
Django
DjangoDjango
Django
 
Mixing Diagram, Tree, Text, Table and Form editors to build a kick-ass modeli...
Mixing Diagram, Tree, Text, Table and Form editors to build a kick-ass modeli...Mixing Diagram, Tree, Text, Table and Form editors to build a kick-ass modeli...
Mixing Diagram, Tree, Text, Table and Form editors to build a kick-ass modeli...
 
Foster - Getting started with Angular
Foster - Getting started with AngularFoster - Getting started with Angular
Foster - Getting started with Angular
 
Django Documentation
Django DocumentationDjango Documentation
Django Documentation
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptx
 

Último

SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Call Us🔝>àŒ’+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>àŒ’+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>àŒ’+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>àŒ’+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfYashikaSharma391629
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
è‹±ć›œUNć­ŠäœèŻ,ćŒ—ćź‰æ™źéĄżć€§ć­ŠæŻ•äžšèŻäčŠ1:1ćˆ¶äœœ
è‹±ć›œUNć­ŠäœèŻ,ćŒ—ćź‰æ™źéĄżć€§ć­ŠæŻ•äžšèŻäčŠ1:1ćˆ¶äœœè‹±ć›œUNć­ŠäœèŻ,ćŒ—ćź‰æ™źéĄżć€§ć­ŠæŻ•äžšèŻäčŠ1:1ćˆ¶äœœ
è‹±ć›œUNć­ŠäœèŻ,ćŒ—ćź‰æ™źéĄżć€§ć­ŠæŻ•äžšèŻäčŠ1:1ćˆ¶äœœqr0udbr0
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...Akihiro Suda
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
How To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROHow To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROmotivationalword821
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 

Último (20)

SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Call Us🔝>àŒ’+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>àŒ’+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>àŒ’+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>àŒ’+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
è‹±ć›œUNć­ŠäœèŻ,ćŒ—ćź‰æ™źéĄżć€§ć­ŠæŻ•äžšèŻäčŠ1:1ćˆ¶äœœ
è‹±ć›œUNć­ŠäœèŻ,ćŒ—ćź‰æ™źéĄżć€§ć­ŠæŻ•äžšèŻäčŠ1:1ćˆ¶äœœè‹±ć›œUNć­ŠäœèŻ,ćŒ—ćź‰æ™źéĄżć€§ć­ŠæŻ•äžšèŻäčŠ1:1ćˆ¶äœœ
è‹±ć›œUNć­ŠäœèŻ,ćŒ—ćź‰æ™źéĄżć€§ć­ŠæŻ•äžšèŻäčŠ1:1ćˆ¶äœœ
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
How To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROHow To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTRO
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 

Django Patterns - Pycon India 2014

  • 1. Django Design Patterns Arun Ravindran
  • 2. About Me Arun Ravindran Blogs and screencasts at arunrocks.com
  • 3. Outline ●Why Design Patterns? ●Does Django follow MVC pattern? ●Model Patterns ●View Patterns ●Template Patterns ●Gyaan on Applying Patterns
  • 4. “ A design pattern is a general reusable solution to a commonly occurring problem within a given context in software design
  • 5. ●Pattern are often elegant and beautiful code ●Repeatable solutions ●Gives a Common Lingo ●Reduces Trial and Error ●Formalizes best practices, say - ○Don’t Repeat Yourself ○Separation of Concerns ○SOLID
 Why Design Patterns?
  • 6. Django and Patterns GoF Pattern Django Component Explanation Observer pattern Signals When one object changes state, all its listeners are notified and updated automatically Template Method Class based generic views Steps of an algorithm can be redefined by subclassing without changing the algorithm’s structure Fowler Pattern Django Component Explanation Active Record Django Models Encapsulates the database access, and adds domain logic on that data Identity Field Id Field Saves a database ID field in an object to maintain identity Template View Django Templates Renders into HTML by embedding markers in HTML
  • 7. Does Django follow MVC? ●MVC is easily misunderstood ●Creators of Django prefer the term MTV ●In reality, Django is an MVC variant ●Compared to classic MVC – ●“Model” is comparable to Django’s Models, ●“View” is usually Django’s Templates ●“Controller” is the entire framework itself
  • 8. Model Patterns ●Pattern: User Profiles ●Pattern: Service Objects ●Pattern: Custom Model Managers
  • 10. User Profiles (contd.) 1.Define the profile model 2.Listen for User model’s post_save signal
  • 11. User Profiles (contd.) 3.Mention your app’s AppConfig 4.Import signals in the AppConfig’s ready 5.(Optional) Inline the User model’s admin
  • 12. User Profiles (contd.) Usage: UserProfile.objects.get_or_create(user=u)
  • 13. Service Objects ●The adage “Fat Models, Thin Views” can lead to frighteningly obese models. ●Service Objects are POPOs that encapsulate a ‘service’ or interactions with a system. ●They are usually kept in a separate file named services.py ●Common use cases: Interactions with external services, Helper tasks, Long- running tasks
  • 14. Service Objects (contd.) 1.Your model delegates to service objects 2.Services are specialized classes:
  • 16. Custom Model Managers (contd.) 1.Use custom manager for common queries 2.Add it to your model
  • 17. View Patterns ●Pattern: Context Enhancers ●Pattern: Access Controlled Views
  • 18. Detour: What is a Mixin? ‱Mixin is a class used to add properties and methods to other classes ‱Composition or Inheritance? Sort of both. TemplateView View ContextMixin Template ResponseMixin
  • 19. Context Enhancers ●Several views might need the same queryset or values in context ●Overriding get_context_data everywhere isn’t DRY ●Instead, use a view mixin:
  • 21. Access Controlled Views (contd.) 1.By using a decorator on a function based view or a class based view 2.Or, by overriding the dispatch method through a mixin
  • 22. Template Patterns ●Pattern: Template Inheritance Tree ●Pattern: Active Link
  • 24. Template Inheritance Tree (contd.) 1.Build a base structure, with placeholders 2.Similar pages are extended from base
  • 26. Active Link (contd.) Here is a simple template-only approach: 1.Every template has the following line 2.The snippet in _navbar.html will be: Custom tags can also be used
  • 27. And the list goes on...
  • 28. Gyaan on Patterns ●How not to use patterns: oDon’t blindly apply. Explain why. oDon’t apply a pattern if you language supports a direct solution oDon’t try to retro-fit everything in terms of patterns oDon’t be afraid to create new patterns.
  • 31. Image Credits ‱http://fooyoh.com/geekapolis_gadgets_wishlist/657945 ‱http://www.bigalspets.ca/multi-stage- canister-filter-c-360.html ‱https://wrapbootstrap.com/theme/sanoor- navbar-WB037R7G3 ‱Monty Python and the Holy Grail ‱Warner Bros