[Solved]-How to create custom CSS "on the fly" based on account settings in a Django site?

3👍

I’ve used option #2 with success. There are 2 decent ways of updating the generated static files that I know of:

  1. Use a version querystring like /special_path.css?v=11452354234 where the v parameter is generated from a database field, key in memcached, or some other persistent file. Version gets updated by admin, or for development you would just make the generation not save if the parameter was something special like v=-1. You’ll need a process to clean up the old generations after some time.

  2. Don’t use a version querystring, but have it look first for the generated file, if it can’t find it, it generates it. You can create a cron job or WSGI app that looks for filesystem changes for development, and have a hook from your admin panel that deletes generations after an update. Here’s an example of the monitoring, which you would have to convert to be specific to your generations and not to Django. http://code.google.com/p/modwsgi/wiki/ReloadingSourceCode#Monitoring%5FFor%5FCode%5FChanges

👤Jordan

1👍

Nice question.

I would suggest to pre-generate css file after colors scheme is saved. This would have positive impact on caching and overall page loading time. You can store your css files in directory /media/css/custom/<id or stometing>/styles.css or /media/css/custom/<id or sth>.css and in template add <link rel="stylesheet" href="/media/css/custom/{{some_var_pointing _to_file_name}}" />

You can also do the trick with some random number or date in css file name that could be changed each time file is saved. Thanks to this browser will load the file immediately in case of changes.

UPDATE: example of using model to improve this example
To make managing of those file easy you can create simple model (one per user):

class UserCSS(models.Model):
    bg_color = models.CharField(..)
    ...
    ...

Fields (like bg_color) can represent parts of your css file. You can ovveride save method to add logic that creates css file for user (by rendering some template).

In case your file format change you can make changes in your’s model definition (with some default values for new fields), make little changes in template and run save method for each exisintg instance of class. This would renew your css files.

That should work nicely.

👤dzida

1👍

Could generate the css and store it in a textfield in the same model as the user profile/settings. Could then have a view to recreate them if you change a style. Then do your option 1 above.

1👍

I would create an md5 key with the theme elements, store this key in the user profile and create a ccs file named after this md5 key : you gain static file access and automatic theme change detection.

Leave a comment