Django:在基于 class 的视图上使用 render_to_string()

Django: Using render_to_string() on a class based view

我正在使用 DetailView 的复杂子 class 来呈现我的模板。

class Test(DetailView):

    template_name = 'my_template.html'
    model = MyModel

    def ..my_methods.. (self, ...):
        ...
        return result

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        ...
        return context

我如何使用此视图才能选择将结果呈现为字符串并将其保存在变量中?

我可以想到 render_to_string(),但我不确定如何将它与基于 class 的视图一起使用。

编辑

a good approach校准dispatch()方法,以便render_to_string()仅在应用给定关键字时。

render_to_string 需要这些参数 template_namedictionarycontext_instance,其中字典和 context_instance 的默认值为 None。根据其定义

Loads the given template_name and renders it with the given dictionary as context. The template_name may be a string to load a single template using get_template, or it may be a tuple to use select_template to find one of the templates in the list. Returns a string.

只需导入函数:

from django.template.loader import render_to_string

并且在继承自 DetailView 的 class 的 get 函数中,只需以给定的定义格式使用它即可。

class Test(DetailView):
    def get(self, request, *args, **kwargs):
        return render_to_string(<template_name>, <dictionary>)

字典作为上下文数据传递给模板。