Ticket #632: dbtemplates2.diff

File dbtemplates2.diff, 8.7 KB (added by Jannis Leidel <jl@…>, 18 years ago)

Completed django.contrib.dbtemplates with loader, sync_templates utility and new documentation

  • django/contrib/dbtemplates/sync_templates.py

     
     1"""
     2Helper function for syncing templates in TEMPLATES_DIRS with the dbtemplates
     3contrib app.
     4"""
     5
     6from django.conf import settings
     7from django.template import TemplateDoesNotExist
     8from django.contrib.dbtemplates.models import Template
     9from django.contrib.sites.models import Site
     10
     11import os
     12import sys
     13
     14try:
     15    site = Site.objects.get_current()
     16except:
     17    site = None
     18
     19def synctemplates(extension=".html", overwrite=False):
     20    """
     21    Helper function for syncing templates in TEMPLATES_DIRS with the
     22    dbtemplates contrib app.
     23    """
     24    tried = []
     25    synced = []
     26    existing = []
     27    overwritten = []
     28   
     29    if site is not None:
     30        for template_dir in settings.TEMPLATE_DIRS:
     31            if os.path.isdir(template_dir):
     32                for dirpath, subdirs, filenames in os.walk(template_dir):
     33                    for file in filenames:
     34                        if file.endswith(extension) and not file.startswith("."):
     35                            filepath = os.path.join(dirpath, file)
     36                            filename = filepath.split(template_dir)[1][1:]
     37                            try:
     38                                try:
     39                                    t = Template.objects.get(name__exact=filename)
     40                                except Template.DoesNotExist:
     41                                    filecontent = open(filepath, "r").read()
     42                                    t = Template(name=filename, content=filecontent)
     43                                    t.save()
     44                                    t.sites.add(site)
     45                                    synced.append(filename)
     46                                else:
     47                                    if overwrite:
     48                                        t.content = open(filepath, "r").read()
     49                                        t.save()
     50                                        t.sites.add(site)
     51                                        overwritten.append(t.name)
     52                                    else:
     53                                        existing.append(t.name)
     54                            except IOError:
     55                                tried.append(filepath)
     56                            except:
     57                                raise TemplateDoesNotExist
     58
     59        if len(existing) > 0:
     60            print "\nAlready existing templates:"
     61            for _existing in existing:
     62                print _existing
     63
     64        if len(overwritten) > 0:
     65            print "\nOverwritten existing templates:"
     66            for _replaced in overwritten:
     67                print _replaced
     68
     69        if len(synced) > 0:
     70            print "\nSuccessfully synced templates:"
     71            for _synced in synced:
     72                print _synced
     73
     74        if len(tried) > 0:
     75            print "\nTried to sync but failed:"
     76            for _tried in tried:
     77                print _tried
     78
     79if __name__ == "__main__":
     80    synctemplates()
  • django/contrib/dbtemplates/models.py

     
     1from django.db import models
     2from django.core import validators
     3from django.contrib.sites.models import Site
     4from django.utils.translation import gettext_lazy as _
     5
     6class Template(models.Model):
     7    """
     8    Defines a template model for use with the database template loader.
     9    The field ``name`` is the equivalent to the filename of a static template.
     10    """
     11    name = models.CharField(_('name'), unique=True, maxlength=100, help_text=_("Example: 'flatpages/default.html'"))
     12    content = models.TextField(_('content'))
     13    sites = models.ManyToManyField(Site)
     14    creation_date = models.DateTimeField(_('creation date'), auto_now_add=True)
     15    last_changed = models.DateTimeField(_('last changed'), auto_now=True)
     16    class Meta:
     17        db_table = 'django_template'
     18        verbose_name = _('template')
     19        verbose_name_plural = _('templates')
     20        ordering = ('name',)
     21    class Admin:
     22        fields = ((None, {'fields': ('name', 'content', 'sites')}),)
     23        list_display = ('name', 'creation_date', 'last_changed')
     24        list_filter = ('sites',)
     25        search_fields = ('name','content')
     26
     27    def __str__(self):
     28        return self.name
  • django/contrib/dbtemplates/loader.py

     
     1# Wrapper for loading templates from the database.
     2
     3from django.conf import settings
     4from django.template import TemplateDoesNotExist
     5from django.contrib.dbtemplates.models import Template
     6from django.contrib.sites.models import Site
     7
     8try:
     9    site = Site.objects.get_current()
     10except:
     11    site = None
     12
     13def load_template_source(template_name, template_dirs=None):
     14    """
     15    Loads templates from the database by querying the database field ``name``
     16    with a template path and ``sites`` with the current site.
     17    """
     18    if site is not None:
     19        try:
     20            t = Template.objects.get(name__exact=template_name, sites__pk=site.id)
     21            return (t.content, 'db:%s:%s' % (settings.DATABASE_ENGINE, template_name))
     22        except:
     23            pass
     24    raise TemplateDoesNotExist, template_name
     25load_template_source.is_usable = True
  • docs/dbtemplates.txt

     
     1============================
     2The database template loader
     3============================
     4
     5Loads templates from the database and is represented by a standard Django
     6model living in `django/contrib/dbtemplates/models.py`_.
     7
     8Installation
     9============
     10
     11To install the database template loader, follow these steps:
     12
     13    1. Put ``'django.contrib.dbtemplates'``,  ``'django.contrib.admin'``
     14       and ``'django.contrib.sites'`` in your ``INSTALLED_APPS`` setting.
     15    2. Add ``'django.contrib.dbtemplates.loader.load_template_source'`` to
     16       ``TEMPLATE_LOADERS``
     17    3. Run the command ``manage.py syncdb``.
     18   
     19.. _INSTALLED_APPS: ../settings/#installed-apps
     20.. _TEMPLATE_LOADERS: ../settings/#template-loaders
     21
     22How it works
     23============
     24
     25``manage.py syncdb`` creates two tables in your database:
     26``django_template`` and ``django_template_sites``. ``django_template`` is
     27a simple lookup table that maps a template name to the text content of the
     28template. The template name is the equivalent to the filename in the
     29filesystem template loader. ``django_template_sites`` associates a
     30template with a site.
     31
     32Templates are loaded by querying the database field ``name`` with a
     33template path as if they were static files. A template with the name
     34``foo.html`` can be loaded with ``get_template('foo.html')``.
     35
     36How to add, change and delete templates
     37=======================================
     38
     39Via the admin interface
     40-----------------------
     41
     42You can find a new "Template" section on the admin index page. Edit
     43templates as you edit any other object in the system.
     44
     45Via the Python API
     46------------------
     47
     48Templates are represented by a standard `Django model`_, which lives in
     49`django/contrib/dbtemplates/models.py`_. You can access template database
     50objects via the `Django database API`_.
     51
     52.. _Django model: ../model_api/
     53.. _django/contrib/dbtemplates/models.py: http://code.djangoproject.com/browser/django/trunk/django/contrib/dbtemplates/models.py
     54.. _Django database API: ../db_api/
     55
     56Via the included syncing utility
     57--------------------------------
     58
     59If you want to add all filesystem based templates from ``TEMPLATES_DIRS``
     60to the database at once, you can use the ``sync_templates.py`` utility.
     61Just run this command::
     62
     63    python /path/to/django/contrib/dbtemplates/sync_templates.py
     64
     65Make sure to substitute ``/path/to/`` with the path to the Django codebase on
     66your filesystem.
     67
     68Alternatively you can import the function ``synctemplates`` from
     69``django.contrib.dbtemplates.sync_templates`` from the Django shell and pass
     70the following parameters:
     71
     72    ``extension`` String:
     73        defines the extension of the files to import, defaults to ".html"
     74
     75    ``overwrite`` Boolean:
     76        overwrites existing templates when True, defaults to False
Back to Top