How should template names be set dynamically using class based views?

Bentley4 picture Bentley4 · Mar 16, 2013 · Viewed 8.5k times · Source

I've searched through the ref and topics of the class based views Django documentation(Django 1.4) but I haven't found any mentioning of this. How do I set template names dynamically using class based views? I'm looking for the class-based equivalent of the following setup:

urls.py

from django.conf.urls.defaults import *
from mysite.views import dynamic

urlspatterns = patterns('', 
    url(r'^dynamic/(?P<template>\w+)/$', dynamic),)
)

views.py

from django.shortcuts import render_to_response

def dynamic(request, template):
    template_name = "%s.html" % template 
    return render_to_response(template_name, {})

Answer

Vladislav Mitov picture Vladislav Mitov · Mar 16, 2013

You need to define get_template_names that returns list of template_names.

from django.views.generic import TemplateView

class DynamicTemplateView(TemplateView):

    def get_template_names(self):
        return ['%s.html' % self.kwargs['template']]