Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Django Class-based Views for Beginners

Spin
April 26, 2016

Django Class-based Views for Beginners

An introduction of Django class-based views for beginners

Spin

April 26, 2016
Tweet

More Decks by Spin

Other Decks in Programming

Transcript

  1. 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)
  2. Class-based View What is Class-based View? ▸ Django views based

    on class ▸ Actually called as Function ▸ Using mixins to add functionality
  3. Class-based View How does it work? Request Django CBV as_view()

    dispatch() get() / post() / put() … Response
  4. 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
  5. 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
  6. Built-in Class-based Generic Views Base Generic Views ▸ django.views.generic.View ▸

    django.views.generic.TemplateView ▸ django.views.generic.RedirectView
  7. Built-in Class-based Generic Views Edit Generic Views ▸ django.views.generic.FormView ▸

    django.views.generic.CreateView ▸ django.views.generic.UpdateView ▸ django.views.generic.DeleteView
  8. 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
  9. 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”
  10. 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?
  11. 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
  12. 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