Setting up Less CSS with Django
Posted on Thu 23 January 2014 in Python
I recently started using Less Css with Django, after using it briefly I found that I did not want to manually compile Less after making changes during development. Using this approach I am able to compile Less client-side during development and have django-compressor compile server-side on live site.
1. Install less via your package manager of choice:
# Using arch linux
sudo pacman -S npm
sudo npm install -g less
# Other distribution
sudo apt-get install npm
sudo npm install -g less
2. Install django-compressor app:
pip install django-compressor
3. Add compressor as installed app:
INSTALLED_APPS = (
# other installed apps
'compressor',
4. Specify less as a precompiler:
COMPRESS_PRECOMPILERS = (
('text/less', 'lessc {infile} {outfile}'),
)
5. Add compressor as a static file finder:
STATICFILES_FINDERS = (
# other static files finder
'compressor.finders.CompressorFinder',
)
6. Compiling less
There are many ways to set this up. A simple, yet effective way is to compile less client-side when debugging and server-side during production. To do this we need to do the following:
- Download less js file from the Less Website
- Create a theme.less (or other name) file
- Now your base.html file will be setup something like this:
{% load staticfiles %} {% load compress %} <!DOCTYPE html> <html> <head> {% if debug %} <link rel="stylesheet" type="text/less" media="all" href="{% static 'less/theme.less' %}" /> <script src="{% static 'js/less-1.6.1.min.js' %}"></script> {% else %} {% compress css %} <link rel="stylesheet" type="text/less" media="all" href="{% static 'less/theme.less' %}" /> {% endcompress %} {% endif %} </head>