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

ⅰ亾dé卋堺 提交于 2019-11-30 02:00:08

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.
        self.foo = request.GET.get('foo', False)

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

@jpic provided a great answer. Inspired from it, I would like to reference the following blog post where the author claims that:

... We cannot override view, as doing so would require overriding as_view(). Overriding dispatch() is appealing (and what I did originally when I presented this talk) because it offers a single simple place to do so, but this defies the logic of dispatch(). Instead, it is best to call set_account() in overrides of both get() and post(). ...

Therefore, one can override the get or post methods and set any self.whatever variables. It feels somehow cleaner.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!