logoalt Hacker News

strogonofflast Wednesday at 12:19 PM0 repliesview on HN

If it’s easier to just write a function view, then sure, just write a function view. I did phrase it specifically: if you want to take stock logic and just override a specific part, then CBV is a pretty intuitive way of doing it.

My point was mostly: stick to function views by default, don’t bother devising your own class-based views in an end project, maybe do if you ship a library and have carefully thought about extension points that are ergonomical for your users, and do take advantage of a pre-existing CBV if it feels like a natural, sustainable, low-LoC solution.

For example, as a default choice, if I need to show a list of items, I would in fact just write a function view. However, once I need more features (the turning point for me is probably pagination), I’d brush up on the docs, subclass a ListView, and enjoy well-tested logic taking care of things for me. In the simplest case I’d just set class attributes without overriding any methods at all; maybe I’d take over get_context_data() to give the template some project-specific variable that doesn’t make sense in context processor. If I need something significantly more custom, I’d switch back to a plain function view and use in it pagination primitives that Django exposes. Done all of the above at different times and I think it worked pretty well.

Yes, it did come with practice and I did ship some spaghetti at first, but I also was a relative noob/junior when CBVs came out.

Fine, it is subjective, so there is more than one way of doing things here, and it is not great, but I still think CBVs have their place.

> I don't own the flow

Sir, this is a framework, we don’t own the flow. (I’m slightly jesting.)

> I like my code to be stupid and linear

I am in the same boat, but to me overriding a CBV method seems pretty stupid.

I used Django for from pre-1.0 (the latest time was in 2021 and that project is still live), been to one PyCon and contributed some really minor fix or two. While I have seen hairy Django codebases, I still think it’s a very sane and the best-documented framework.