Using Django pipeline to add hash to static files


Using Django pipeline to add hash to static files

Why do I need hash static files?

LookHow to develop and deploy front end code in large companies?Zhang Yunlong’s answer.

In this way, when the static file has been modified, it will be very convenient to get the latest modified version, while the unmodified static file will still use the cache. This avoids the embarrassment of not updating the user’s static files after modification, and can make full use of the cache.




sudo mkdir /opt/projects
git clone
cd django_pipeline_demo
ln -s $(pwd) /opt/projects
ln -s /opt/projects/django_pipeline_demo/deploy/nginx/django_pipeline.conf /etc/nginx/sites-enabled
pip install -r requirements.txt
python runserver
nginx -s reload
VIM / etc / hosts add Django_ pipline_

Django’s Library pipeline

mako, django-mako, django-pipeline-demo

The effect is this, todjango_pipeline_demoFor example.

Let’s talk about the final usage first

  1. Debug must be false (online is false). If it is true, Django will be used to find static files by default instead of pipeline.
  2. python collectstatic
  3. Restart Django project

Key code explanation Several configurations of,
How to install and configure Django pipeline, please move tofile.

Explain several collection related configurations

# python  After collectstatic, the file will be thrown to static_ Under root
STATIC_ROOT = './statics'

#Django's templates will be found in these directories
    os.path.join(BASE_DIR, 'templates'),

#When developing, collectstatic will look up the path of CSS and then drop it to static_ Under root
#After using pipeline, hash code, such as CSS, will be added to the static file/ index.css
#After collectstatic, it will become CSS/ index.as1df14jah8dfh .css
    os.path.join(BASE_DIR, "static_dev"),


This is to define a URL with Mako. After static files are imported with this URL, the hash version can be found.

from import staticfiles_storage

<%def name='url(file)'><%
    url = staticfiles_storage.url(file)
    url = file


First, import / common / static_ pipeline.html , where static files need to be referenced${ static.url ('unhash file path ')}

<%namespace name='static' file='/common/static_pipeline.html'/>
    <link rel="stylesheet" href="${static.url('css/index.css')}" type="text/css" media="all" />