Overview

In this tutorial you will learn how to compress your static files i.e., javascript (.js) and css (.css) files.

You can clone the project from the below link, if you dont have started the project. It has all the minimal configuration required for the tutorial.

Github Repo link: https://github.com/nitinraturi/django-compressed-minified-sample-project

Install Dependencies

# Install Memcache

sudo apt-get install memcached # Ubuntu

brew install memcached # For mac

# start memcache
sudo service memcached start # Ubuntu

brew services start memcached # Mac

# If using virtual environment, activate it
source venv/bin/activate

pip install python-memcached
pip install django-compressor
pip install django-htmlmin

# django-compressor (Compresses linked and inline JavaScript or CSS into a single cached file)
# django-htmlmin (HTML minifier for Python frameworks)

Configure settings.py

# settings.py

# Configure memcache if not configured before

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': '127.0.0.1:11211',
    }
}

Memcached runs through localhost port 11211 by default, so there’s no further configuration here. There are other options to have a dedicated Memcached server or have Memcached store files locally. Django documentation has more information on how to set that up.

# settings.py
# Add compressor to your installed apps

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.sitemaps',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # Custom Apps
    'apps.blog',

    # Third Party Packages
    'compressor',
]

Add middlewares

# settings.py

MIDDLEWARE = [
    # add these below 3 middleware at the first position
    'django.middleware.gzip.GZipMiddleware',
    'htmlmin.middleware.HtmlMinifyMiddleware',
    'htmlmin.middleware.MarkRequestMiddleware',

    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

Configure static files settings

# settings

# Change these as per your project
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")]
STATIC_ROOT = os.path.join(BASE_DIR,"static_root")
# settings.py

#staticfiles finder

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',

    # Add this
    'compressor.finders.CompressorFinder',
)

Add compressor and minifier settings

# settings

# Compressor and minifier config
COMPRESS_ENABLED = True
COMPRESS_CSS_HASHING_METHOD = 'content'
COMPRESS_FILTERS = {
    'css':[
        'compressor.filters.css_default.CssAbsoluteFilter',
        'compressor.filters.cssmin.rCSSMinFilter',
    ],
    'js':[
        'compressor.filters.jsmin.JSMinFilter',
    ]
}
HTML_MINIFY = True
KEEP_COMMENTS_ON_MINIFYING = True

Lets compress static files in templates

Basic example:

<!-- your_template.html -->
{% load compress %}

{% compress css %}
    <link rel="stylesheet" href="/static/css/one.css" type="text/css" charset="utf-8">
    <style type="text/css">p { border:5px solid green;}</style>
    <link rel="stylesheet" href="/static/css/two.css" type="text/css" charset="utf-8">
{% endcompress %}

{% compress js %}
    <script src="/static/js/one.js" type="text/javascript" charset="utf-8"></script>
    <script type="text/javascript" charset="utf-8">obj.value = "value";</script>
{% endcompress %}

<! -- Adding the inline parameter will put the content directly to the rendered page instead of a file -->

{% compress js inline %}
<script src="/static/js/one.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">obj.value = "value";</script>
{% endcompress %}

 

# generated files will look something like this

# CSS
<link rel="stylesheet" href="/static/CACHE/css/output.f7c661b7a124.css" type="text/css" charset="utf-8">

# JS
<script src="/static/CACHE/css/output.f7c661b7a124.css" type="text/css" charset="utf-8"></script>

# Dont worry about run your server and you can check your source code.

 

Compress and Run server

python manage.py collectstatic
python manage.py compress --force
python manage.py runserver