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

前端 未结 2 585
星月不相逢
星月不相逢 2020-12-24 06:38

I trying out Django\'s class based views (CBVs).

class BlahView(TemplateView):
    template_name = \'blah/blah.html\'
    def get_context_data(self, **kwargs         


        
2条回答
  •  北荒
    北荒 (楼主)
    2020-12-24 06:49

    @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.

提交回复
热议问题