ivsiquadrus
ivsiquadrus

Reputation: 65

Django changing template_name in get_context_data dynamically

how do I override the template_name of a TemplateView based on the context in get_context_data? In other words, I would like to find a way to change the template rendered according to my context.

The following is modified from my current code and it does not work:

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

I can confirm that the line changing template_name is executed and it is indeed set to "folder/template2.html" at that point, but the actual page that gets rendered still looks like the original (template1.html) instead.

Any helpful insight would be deeply appreciated. Thank you very much!

Upvotes: 1

Views: 1228

Answers (1)

Abdul Aziz Barkat
Abdul Aziz Barkat

Reputation: 21807

When you write:

template_name = "folder/template2.html"

You are just declaring a local variable which will never get used. Instead you want to modify the instance variable which you can access / modify by accessing 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

Upvotes: 2

Related Questions