首页 > 解决方案 > Django 动态更改 get_context_data 中的 template_name

问题描述

如何根据上下文覆盖template_namea ?换句话说,我想找到一种方法来根据我的上下文更改呈现的模板。TemplateViewget_context_data

以下是从我当前的代码修改的,它不起作用:

class FooPage(TemplateView):
  template_name = "folder/template1.html"
  
  def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['myvariable'] = MyModel.objects.get(pk=kwargs['some_criterion']).variable
    if "text" in context['myvariable']:
      template_name = "folder/template2.html" # This line does get executed
    return context

我可以确认换行template_name已执行,并且确实设置"folder/template2.html"为该点,但是呈现的实际页面仍然看起来像原始的 ( template1.html) 。

任何有用的见解将不胜感激。非常感谢!

标签: pythondjangodjango-viewsdjango-templates

解决方案


当你写:

template_name = "folder/template2.html"

您只是在声明一个永远不会被使用的局部变量。相反,您想修改可以通过以下方式访问/修改的实例变量self

class FooPage(TemplateView):
    template_name = "folder/template1.html"
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['myvariable'] = MyModel.objects.get(pk=kwargs['some_criterion']).variable
        if "text" in context['myvariable']:
            self.template_name = "folder/template2.html"
        return context

推荐阅读