top | item 17418501

(no title)

purrpit | 7 years ago

Maybe not just Newbies, but I often notice even seasoned Django developers cribbing about Django's Class Based Views (CBV). I don't really understand why to be honest. There are many blog posts that express regretting the time invested in CBV by their respective authors by pointing out all sorts of pitfalls they fell into during usage. My ex-boss hates it as well, he even banned it from usage among developers. IMHO, it's was a great new introduction in version 1.3.

I hear them discuss about the difficulties and time it takes to implement some views which involves complex logic and more than one entity per view. How to embed a Form inside a Paginated page for example: to use a FormView or to use a ListView or both, followed by a long day of trying to exit a maze full of dead-ends

My advice to Newbies and other people who are struggling with CBV is:

1: You are probably not struggling with the concept of class based views.. just with Django's generic views module

2: Stop stressing about not being able to understand what each Django generic view class does, or it's Mixin classes. Instead refer to ccbv.co.uk and source code extensively - not just the docs.

3: If you are not able to fit every logic you want to fit inside your view using a generic Django view class.. Then just spin up your own class from Mixins or django-braces like nice apps or from object.

4: Remember, one basic upgrade you get from using Classes vs Functions is the ability to extend. If your views can not take advantage of this then you probably don't need a class based view, function based is fine. I almost always keep a base view class with me, often call it a ContextMixin(object) and use it in every view so that i can have some common context variables available in my every template.

discuss

order

ricw|7 years ago

Or just don’t use class based views. Simple function views do the job just as well while not obscuring code “behind a magic wall”.

collinmanderson|7 years ago

I personally don't use them, except for date-based pages. I find plain old functions the most clear, even if there's a little bit of duplication.