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
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:
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
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
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.