Hacker News new | ask | show | jobs
by Alex3917 1659 days ago
> function based views

Class-based views, in their most basic form, are a lot easier to read. E.g. look at the DRF CBVs I have here:

https://github.com/Alex3917/django_for_startups/blob/main/dj...

If you can avoid Generic CBVs (things like ListView) and inheritance, then the only difference between FBVs and CBVs is that CBVs make it easier to see what's a GET / PUT / POST / DELETE by adding some syntax highlighting that makes it easier to visually differentiate which code goes to which method. You don't need to know anything about classes in Python in order to use them.

It's not at all difficult to switch from FBVs to CBVs later, and most people (myself included) use FBVs when getting started. But I'd also say that if you're willing to push through the initial discomfort and spend the extra half hour or whatever on YouTube in order to understand them, then you do get a little bit of a nicer overall development experience.

3 comments

Alex has written an excellent blog about Django best practices for startups. It contains wonderful insights about how you should structure code and why you should structure it that way. It has helped us a ton! https://news.ycombinator.com/item?id=27605052
The blog post itself is also archived here: http://archive.today/1cNZb
I usually have a FBV handler (foo_handler) that just passes along all the required parameters to foo_get, foo_post, etc, and then takes the return value of those and wraps it in a HttpResponse/JsonResponse.

That way my actual view logic doesn't have to deal with anything http, and it makes testing them way simpler.

Class views are fine. Even just a TemplateView saves some effort, but it comes with learning some Django magic about the life cycle of the view to load data in and out and what methods to implement. I still recommend it. You don’t have to fully embrace it and it lets you avoid repeating a lot of code.
My recommendation for learning class-based views is to use a good editor or IDE that allows you to drill down into the library code easily. In PyCharm/IntelliJ I can just command-click on the TemplateView symbol and see its implementation, and do so recursively until I've unraveled the entire thing.
Agreed. Django's documentation is pretty light on the order in which certain functions will be executed and diving into the code is the only way I've been able to understand what happens when handling forms and views.
http://ccbv.co.uk/ is a pretty useful resource for learning class based views...