I am working on a project where some templates are stored as part of a ‘theme’ in the database. Because of this, I’m not able to leverage a lot of Django’s nice template rendering functionality immediately. For example:
# Instead of this...
return render_to_response('path/to/template', arguments, context_instance=context)
# Have to do this...
template = Template(model.template_field)
context.update(arguments)
return HttpResponse(template.render(context))
This is fine, however, the problem that I’ve run in to is including sub-templates. If, for example, model.template_field looks like this…
<html>
<head>
{% include head_extra %} <!-- Another DB field -->
</head>
<body>
{% include body_extra %} <!-- Another DB field -->
</body>
</html>
…Then Django will complain that the template doesn’t exist (because there is no template with that name).
How can I include the sub-templates in a dynamically created template?
Edit (Ignoring the database constraint, and providing more details):
I want users to be able to define their own templates, either via a file upload, or through some editor.
I would like them to be able to include sub-templates via {% include %}, but I don’t want the user to have to worry about where they are including from. Hence, I just want them to include like this: {% include extra_head %}. However, django certainly needs to know where the templates are located in order to load them.
What do people typically do when they want user defined templates in django?
If you are willing to waive the requirement that
{% include %}statements are needed, you can do things by hand if you try something like this in your view……With a ‘template’ like this:
This pattern can work for more deeply nested elements as well provided you build the lowest level templates first. You can include existing templates via
render_to_string, but you can still run into problems if you ever want to include something within a loop context.A bit kludgy, and not exactly what you’re looking for, but it will work.