Content: Blog

All

Django Compressor and django CMS

Jacob Rief

Aug. 30, 2019

An update to Django Compressor improves its usability in django CMS projects.

If you are using django-CMS, chances are high that you also use django-sekizai. This app is used to group JavaScript and CSS files from different components of your Django project to their intended positions inside the HTML’s head-block and at the end of the body-block. Especially for django-CMS plugins, this is very convenient for separation of concern, because it only includes those files in the final HTML output, if they are required. A similar concept is used in modern JavaScript frameworks, such as React, VUE.js, and others.

Since django-sekizai groups those files, django-compressor can be used to concatenate and optionally compress them into one single file. This helps to reduce the number of subrequests when loading a page, ideally to one per CSS and one per JavaScript. In the base template of a django-CMS page, typically we add

{% render_block "css" postprocessor "compressor.contrib.sekizai.compress" %}

to the head-block and

{% render_block "js" postprocessor "compressor.contrib.sekizai.compress" %}

at the end of the body-block.

Sometimes however, django-CMS plugins have to include files hosted elsewhere, for instance from a CDN. If we add these includes to a Sekizai {% addtoblock "css" %}…{% endaddtoblock %} or {% addtoblock "js" %}…{% endaddtoblock %}, everything works fine until we go to production and django-compressor kicks in. Since these files are hosted beyond the reach of django-compressor, the latter must raise an exception. 

In django-compressor version 2.3, this finally has been resolved by separating and grouping externally hosted includes from internally ones. The former then are grouped at the beginning of a Sekizai’s {% render_block … %}, while the latter are concatenated and compressed.
Details of this new feature are explained in the Django Compressor documentation


Want to post your article here?

Contact us