Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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, {})
like image 201
Bentley4 Avatar asked Mar 16 '13 10:03

Bentley4


People also ask

How does Django define class based views?

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.

What is Template View Django?

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.

What are Django generic views?

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.


1 Answers

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']]
like image 96
Vladislav Mitov Avatar answered Sep 28 '22 04:09

Vladislav Mitov