Monday, April 3, 2017

Re: Will function based views ever be deprecated?

There's a little bit of vocabulary overload going on that I can't help but point out, as it confused me when I encountered it.

There is a difference between Class-Based Views (CBV) and Generic Class-Based Views (GCBV). They were both introduced at the same time, and so it is easy to get them confused, but they serve very different purposes.

When referring to CBV, there is actually only a single CBV, called View. Every other class-based view provided by Django is a generic view! The goal of these views is to provide pre-defined, slightly-customizable behavior. The fact that they are objects (class-based) is secondary. They are called GCBV for historical reasons: to make a difference between the generic view _functions_ that preceded them.

As James points out, a view is simply a Python callable that receives a request and returns a response. To that extent, the View class and function views are _almost_ equivalent. View provides two extra things over a function view: (1) automatic handling of the OPTIONS HTTP method and (2) denial of HTTP methods not explicitly defined. The methods defined on subclasses of View map directly to HTTP verbs. As developers define class methods named after HTTP methods, View will automatically change the response returned by an OPTIONS request and allow those methods to return data.

Of course, a function view can be implemented to handle OPTIONS and deny HTTP methods not explicitly implemented. Django even provides a decorator for the latter, linked below.
https://docs.djangoproject.com/en/stable/topics/http/decorators/#django.views.decorators.http.require_http_methods

My personal opinion is that language is power, and I find the terms Class-Based Views and Generic Class-Based Views misleading. I'd prefer to simply call the latter Generic Views, as their object nature is not their utility. In an attempt to distance the documentation from the CBV vs GCBV, I'd consider calling View instances and subclass-instances "Object Views". That said, when I suggested this at DjangoCon US 2015, my suggestions seemed polarizing, so make of this what you will.

I feel pretty strongly about this topic, and gave a talk about it at the same conference: https://www.youtube.com/watch?v=BJiOERA49ZQ

I hope this is helpful!
Andrew
http://jambonsw.com
http://django-unleashed.com



--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/BD0905CB-9D16-4F9A-8CBD-7115B3E46303%40andrewsforge.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment