Grokking Technology

Dynamic CSS in Django

or a while I have been thinking of having my Django sites include CSS styling from a database; for instance having different themes that can be switched on and off at will. It took me a while - with some help from Django users & docs - to figure out how to do it.

My eventual solution uses a template file containing variable names where colours should go; the variables get their values generated at run-time from the database.

Designing and populating a database to manage the variables is pretty straight-forward; generating the CSS file is not a common feature it seems hence this posting.

The Template

Suppose we have a template containing CSS which we want to alter dynamically; something like this

#afc-portal-globalnav  {
  background-color: {{ globalnav_background_normal }};
  border: 1px solid {{ globalnav_border_colour }};

#afc-portal-globalnav ul {
  color: {{ globalnav_colour_normal }};

Here we have a few variable names (globalnav_background_normal, globalnav_border_colour, etc) we want to replace with colours picked from our database.

The View

We can create a Functional View which sets-up the page, queries the database, generates from the template and returns the page

In the first part, we make sure the response will be of the appropriate type. We need to do more here to make sure the page will be cached appropriately - we do not want to be generating this file for every query.

def themecss(request):

 # Create the HttpResponse object with the appropriate header.

 response = HttpResponse(content_type='text/css')

Now we can query the database and assemble the key, value pairs for the variables with their colours.

context = {}

for item in Tag.objects.all():
  context[item.tag] = item.colour

And finally we load the template with our variables and return the page.

t = loader.get_template('afc_skin_theme.css')
c = Context(context)response.write(t.render(c))
return response

With this in place and our database populated with an appropriate structure, we can define an url to call the view and include this in our regular pages. Without any caching controls, the styling can be changed more or less immediately.

Dead easy when you know how, eh?

Page created on Sat 30 Jan 2021 by Andy Ferguson