3. Function-based View
What is Function-based View?
▸ A Django views is a function that :
▸ Take an HTTP request as the input
▸ Turn it into a HTTP response
▸ a.k.a Function-based Views (FBVs)
16. Mixins
What is Mixin in Python?
▸ Actually, mixins are ordinary Python classes
▸ Provides functionality to be inherited
▸ But isn’t meant to be instantiated on its own
19. Mixins
Rule of thumb
▸ Base view classes provided by Django always go to the
right.
▸ Mixins go to the left of the base view.
▸ Mixins should inherit from Python’s built-in object type
▸ Keep shallow inheritance chain
20. Mixins - Rule of thumb
Base view classes provided by Django always go to the right
21. Mixins - Rule of thumb
Mixins go to the left of the base view
22. Mixins - Rule of thumb
Mixins should inherit from Python’s built-in object type
39. The Dark Side
The Dark Side of Mixins
▸ Easy to lose track of the origin of your methods
▸ You may actually polluting the class namespace
40. The Dark Side
The Dark Side of Generic CBVs
▸ Flow control is totally hidden
▸ The order of execution may not be obvious to anyone else
▸ More difficult to debug
▸ To understand what’s going on. You have to read the API
docs, or even the source code of CBVs …
▸ Remember? “Explicit is better than implicit”
43. Takeaways
FBVs or CBVs ?
▸ Does the Generic CBVs closely match what you need?
▸ Can you use a CBV just by overriding some attributes?
▸ Do you need to subclass your views to create some views?
44. Takeaways
Guidelines
▸ Keep your view simple
▸ Never repeat code in your views
▸ Only handle presentation logic in views
▸ Keep your mixins simpler
▸ Don’t use CBVs to write 403, 404… error handlers. Use
FBVs instead
47. Resources
Books
▸ 「Two Scoops of Django: Best Practices for Django 1.8」
▸ Chap 8 Function-and-Class-Based Views
▸ Chap 9 Best Practices for Function-Based Views
▸ Chap 10 Best Practices for Class-Based Views