It seems to me that in Django's generic class-based views, the parameters request
, args
and kwargs
travel from method to method, both as view instance attributes, as well as method arguments.
What do I mean exactly?
Class django.views.generic.base.View
, defines the following function, called by its as_view
method:
def view(request, *args, **kwargs):
self = cls(**initkwargs)
if hasattr(self, 'get') and not hasattr(self, 'head'):
self.head = self.get
self.request = request
self.args = args
self.kwargs = kwargs
return self.dispatch(request, *args, **kwargs)
This function first sets request
, args
and kwargs
as view instance attributes, and then invokes the view's dispatch
method with all these as arguments. What exactly is the purpose of this, if any? Isn't it redundant?
Although some CBV methods (like
dispatch()
) have the arguments passed to them directly, others do not. And, of course, you might want to define your own methods that have access to these values without having to pass them around.Part of the point of CBVs is that you don't have to think as much about the flow of control (who is calling what); instead, you can just override small bits of functionality (e.g.
get_context_data()
). So it's more natural to think of data attached to the object rather than arguments that are passed around from method to method.Why not get rid of the arguments entirely? Probably because it's a better match to the legacy of function-based views. For example, many FBVs will have a CBV equivalent that uses the exact same code in the
get()
method.