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.