从自定义 class 视图继承的基于 Class 的视图在父视图中看不到上下文变量

Class based view that inherits from a custom class based view does not see context variables in parent

我写了一个基于 Class 的视图,它作为其他几个基于 class 的视图的基础视图。所以其他基于class的视图只是subclassing基础视图,但是subclassed视图没有得到get_context_data或[=29=的效果] 函数,因此当使用视图子 class 基本视图执行请求时,基本视图中设置的上下文变量不会发送到模板,它们仅在使用基本视图本身时发送。

Class 基于视图:

class PortfolioNewBase(CreateView):
    url_name = ''
    post_req = False

    def form_valid(self, form):
        self.post_req = True
        return super(PortfolioNewBase, self).form_valid(form)

    def get_context_data(self, **kwargs):
        context = super(PortfolioNewBase, self).get_context_data(**kwargs)
        context['profile_id'] = self.kwargs['profile_id']
        context['post_req'] = self.post_req
        return super(PortfolioNewBase, self).get_context_data(**kwargs)

    def get_success_url(self):
        return reverse(self.url_name, args=self.kwargs['profile_id'])

当创建一个新的基于 class 的视图时,它是将使用此代码的视图之一,由于某种原因它无法访问 "profile_id" 或 "post_req" 变量,它不会发送到模板,但如果您只使用上面编写的基本视图,该视图将发送变量,以便它们在视图中可用。

基于 class 的视图之一使用上面编写的基本视图的代码:

class PortfolioNewDividend(PortfolioNewBase):
    model = Dividend
    form_class = DividendForm
    template_name = 'plan/portfolio/new/new_dividend.html'
    url_name = 'plan:investment-info-dividends-new'

表单有效,但由于某种原因,父项 get_context_data 中的变量显然没有被继承,这就是这里的要点, form_valid 函数没有被继承运行 或者,基于 PortfolioNewDividend class 的视图对 POST 请求的 post_req 的值仍然为 False。

为什么在使用该视图执行请求时 PortfolioNewDividend 未 运行 启用 get_context_data 和 form_valid 功能,但如果您使用基础功能,则功能 运行只有 clase(上面写的)?

其中一个 super 调用太多。变化如下:

def get_context_data(self, **kwargs):
    context = super(PortfolioNewBase, self).get_context_data(**kwargs)
    context['profile_id'] = self.kwargs['profile_id']
    context['post_req'] = self.post_req
    return context  # You must actually return the modified context!