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, {})
A view is a callable which takes a request and returns a response. This can be more than just a function, and Django provides an example of some classes which can be used as views. These allow you to structure your views and reuse code by harnessing inheritance and mixins.
Django provides several class based generic views to accomplish common tasks. The simplest among them is TemplateView. It Renders a given template, with the context containing parameters captured in the URL. TemplateView should be used when you want to present some information on an HTML page.
Django's generic views were developed to ease that pain. They take certain common idioms and patterns found in view development and abstract them so that you can quickly write common views of data without having to write too much code.
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']]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With