Setup¶
Get the source from the Git repository or install it from the Python Package Index by running
pip install django-dbtemplates.Follow the instructions in the INSTALL file
Edit the settings.py of your Django site:
Add
dbtemplatesto theINSTALLED_APPSsettingCheck if
django.contrib.sitesanddjango.contrib.adminare inINSTALLED_APPSand add if necessary.It should look something like this:
INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'django.contrib.flatpages', # .. 'dbtemplates', )
Add
dbtemplates.loader.Loaderto theTEMPLATES.OPTIONS.loaderslist in the settings.py of your Django project.It should look something like this:
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ # your template dirs here ], 'APP_DIRS': False, 'OPTIONS': { 'context_processors': [ 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.debug', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.template.context_processors.tz', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.request', ], 'loaders': [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', 'dbtemplates.loader.Loader', ], }, },
]
The order of
TEMPLATES.OPTIONS.loadersis important. In the former example, templates from the database will be used as a fallback (ie. when the template does not exists in other locations). If you want the template from the database to be used to override templates in other locations, putdbtemplates.loader.Loaderat the beginning ofloaders.
Sync your database
python manage.py migrateRestart your Django server
Usage¶
Creating database templates is pretty simple: Just open the admin interface of your Django-based site in your browser and click on “Templates” in the “Database templates” section.
There you only need to fill in the name field with the identifier, Django
is supposed to use while searching for templates, e.g.
blog/entry_list.html. The content field should be filled with the
content of your template.
Optionally, by leaving the content field empty you are able to tell
dbtemplates to look for a template with the name by using Django’s
other template loaders. For example, if you have a template called
blog/entry_list.html on your file system and want to save the templates
contents in the database, you just need to leave the content field empty to
automatically populate it. That’s especially useful if you don’t want to
copy and paste its content manually to the textarea.