Is it okay to set instance variables in a Django class based view?

According to the source of django.views.generic.base.View.as_view:

  • on django startup, as_view() returns a function view, which is not called
  • on request, view() is called, it instantiates the class and calls dispatch()
  • the class instance is thread safe

According to the source of django.views.generic.base.View.__init__, the request object is out of scope at this point so you can’t parse it in your own constructor overload.

However, you could parse the request and set class view instance attributes in an overload of django.views.generic.base.View.dispatch, this is safe according to the source:

class YourView(SomeView):
    def dispatch(self, request, *args, **kwargs):
        # parse the request here ie. = request.GET.get('foo', False)

        # call the view
        return super(YourView, self).dispatch(request, *args, **kwargs)

Leave a Comment