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

Weitere Àhnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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
 

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

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

KĂŒrzlich hochgeladen

Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
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
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
(Genuine) Escort Service Lucknow | Starting â‚č,5K To @25k with A/C đŸ§‘đŸœâ€â€ïžâ€đŸ§‘đŸ» 89...
(Genuine) Escort Service Lucknow | Starting â‚č,5K To @25k with A/C đŸ§‘đŸœâ€â€ïžâ€đŸ§‘đŸ» 89...(Genuine) Escort Service Lucknow | Starting â‚č,5K To @25k with A/C đŸ§‘đŸœâ€â€ïžâ€đŸ§‘đŸ» 89...
(Genuine) Escort Service Lucknow | Starting â‚č,5K To @25k with A/C đŸ§‘đŸœâ€â€ïžâ€đŸ§‘đŸ» 89...gurkirankumar98700
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
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
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 

KĂŒrzlich hochgeladen (20)

Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Call Girls In Mukherjee Nagar đŸ“± 9999965857 đŸ€© Delhi đŸ«Š HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar đŸ“±  9999965857  đŸ€© Delhi đŸ«Š HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar đŸ“±  9999965857  đŸ€© Delhi đŸ«Š HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar đŸ“± 9999965857 đŸ€© Delhi đŸ«Š HOT AND SEXY VVIP 🍎 SE...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
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
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
(Genuine) Escort Service Lucknow | Starting â‚č,5K To @25k with A/C đŸ§‘đŸœâ€â€ïžâ€đŸ§‘đŸ» 89...
(Genuine) Escort Service Lucknow | Starting â‚č,5K To @25k with A/C đŸ§‘đŸœâ€â€ïžâ€đŸ§‘đŸ» 89...(Genuine) Escort Service Lucknow | Starting â‚č,5K To @25k with A/C đŸ§‘đŸœâ€â€ïžâ€đŸ§‘đŸ» 89...
(Genuine) Escort Service Lucknow | Starting â‚č,5K To @25k with A/C đŸ§‘đŸœâ€â€ïžâ€đŸ§‘đŸ» 89...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
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
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 

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