Marcos Hemann
Marcos Hemann

Reputation: 11

Django TemplateView get template from a field from DB

I want create a templateview but need to use a editable template on-the-fly, to this i can set a template from a code stored inside a field from a table.

# some_app/views.py
from django.views.generic import TemplateView

class AboutView(TemplateView):
    template_name = "about.html"  -> from table.field

Some ideia?

Great @WillemVanOnsem nice solution. But to complicate more, if i want to do in Django Rest like:

class FormularioDisplayView(APIView):
    renderer_classes = [TemplateHTMLRenderer]

    def get(self, request, pk):
        formulario = get_object_or_404(Formulario, codigo=pk)
        serializer = FormularioDisplaySerializer()
        template_data = TemplateData.objects.get(name='model_01')

        return Response({'serializer': serializer, 'formulario': formulario})  -> Render  using template_data.template as the template

Upvotes: 1

Views: 384

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476659

We can alter the TemplateView to obtain the content of a template from the database. For example we can have a model like:

# app/models.py

class TemplateData(models.Model):
    name = models.CharField(max_length=128, unique=True)
    template = models.CharField(max_length=32768)

Here the TemplateData model thus associates a name with the content of a template.

Next we can implement a TemplateFromDatabaseView where we override the render_to_response method [Django-doc]:

# app/views.py

from app.models import TemplateData
from django.http import HttpResponse
from django.views.generic import TemplateView
from django.template import Template, Context

class TemplateFromDatabaseView(TemplateView):

    def render_to_response(self, context, **response_kwargs):
        template_data = TemplateData.objects.get(name=self.template_name)
        return HttpResponse(
            Template(template_data.template).render(
                RequestContext(self.request, context)
            )
        ), **response_kwargs)

Then you can subclass it, for example with:

# app/views.py

# …

class AboutView(TemplateFromDatabaseView):
    template_name = 'database_template_name'

Of course that means you need to add a TemplateData object to the database with as name the 'database_template_name' and with as template field, the content you want to render.

Upvotes: 2

Related Questions