# your_app/models.py:

from django.contrib.contenttypes.models import ContentType
from django.db import models

class TemplateTypes(models.Model):

    type_name = models.CharField(max_length=80)
    content_type = models.ForeignKey(ContentType, blank=True, null=True)
    
    def __unicode__(self):
        return self.type_name

class Templates(models.Model):

    slug = models.CharField(max_length=80)
    template_type = models.ForeignKey('TemplateTypes')
    template_body = models.TextField()
    
    def __unicode__(self):
        return self.slug


# your_app/loaders.py:

from django.template import loader, TemplateDoesNotExist
from models import *

class DatabaseLoader(loader.BaseLoader):

    is_usable = True

    def load_template_source(self, template_name, template_dirs=None):
        try:
            return Templates.objects.get(slug=template_name).template_body, template_name
        except Templates.DoesNotExist:
            raise TemplateDoesNotExist, template_name


# your_project/settings.py

TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
    'your_project.your_app.loaders.DatabaseLoader',
)


# your_app/admin.py (OPTIONAL):

from django.conf import settings
from django.contrib import admin
from django.forms import ModelForm
from models import *

class TemplatesAdminForm(ModelForm):

    class Media:

        css = {
            'all': (
                '%syour_app/css/codemirror.css' % settings.STATIC_URL,
            )
        }

        js = (
            '%syour_app/js/jquery.min.js' % settings.STATIC_URL,
            '%syour_app/js/codemirror.js' % settings.STATIC_URL,
            '%syour_app/js/xml.js' % settings.STATIC_URL,
            '%syour_app/js/javascript.js' % settings.STATIC_URL,
            '%syour_app/js/css.js' % settings.STATIC_URL,
            '%syour_app/js/htmlmixed.js' % settings.STATIC_URL,
            '%syour_app/js/htmlembedded.js' % settings.STATIC_URL,
            '%syour_app/js/admin-connector.js' % settings.STATIC_URL,
        )

class TemplatesAdmin(admin.ModelAdmin):

    form = TemplatesAdminForm

admin.site.register(Templates, TemplatesAdmin)


# your_app/static/your_app/js/admin-connector.js (OPTIONAL):

$(document).ready(function(){
    var editor = CodeMirror.fromTextArea(document.getElementById("id_template_body"), {
        lineNumbers: true,
        matchBrackets: true,
        mode: "application/x-ejs",
        indentUnit: 4,
        indentWithTabs: true,
        enterMode: "keep",
        tabMode: "shift"
    });
});