I’ve been working on a django blogger clone. It has many interesting features includding email blogging, gadgets, followers, many authors per blog, feed agregation, fully customizable colors and themes.
This time I want to write how do we (I was working with a classmate) solved the problem of dynamic themes. First we wanted the themes to be dynamic that means the site administrator can add or edit themes using the django administration site.
First we created a model called Theme
class Theme(models.Model):
name = models.CharField(max_length=40, unique=True)
description = models.TextField(blank=True)
slug = models.SlugField(max_length=50, unique=True, editable=False)
base_html = models.FileField(upload_to=upload_to('themes/'))
style_css = models.FileField(upload_to=upload_to('themes/'),
blank=True, null=True)
preview = models.ImageField(upload_to=upload_to('themes/'))
def __unicode__(self):
return '%s' % self.name
The name, description, preview and slug fields are obvious. We included a base_html file wich is supoused to be a base template used for all the weblog templates. A css style file is also needed for styling the weblog.
Many themes require adicional images so we created another model like this:
class ImageTheme(models.Model):
theme = models.ForeignKey(Theme)
image = models.ImageField(upload_to=upload_to_image('themes/'))
We expected each base.html to declare a content, and a sidebar block. So this blocks are used in the weblog templates to display the information.
The trick is to pass the tempalte name from the view. So the weblog tempaltes are going to inherit dynamically a base template but that is too much work so we created the following method in the blog model:
def get_theme(self):
if self.theme:
location = self.theme.base_html._get_url()
name_list = location.split('/')
s = len(name_list)
return '%s/%s' % (name_list[s-2], name_list[s-1])
return 'default_theme.html'
So in every weblog template we can have something like:
{% extends blog.get_theme %}
You also must tell template loaders where are your themes so maybe you can something like:
TEMPLATE_DIRS = (
'/home/html/django_templates',
'/path/to/your/templates/files/directory/',
)
in your settings.py
And remember that /path/to/your/templates/files/directory/ must be a directory inside your MEDIA_ROOT so django can upload the new themes there.