Pol Alvarez Vecino
Pol Alvarez Vecino

Reputation: 187

Serve different Static files on devel and production in Django

I have a production and local DJANGO development environment. To push things to production we have a deployer which minifies and gzips all CSS and JS files.

To serve them on production I need to call them like

  <link rel="stylesheet" href="{{ STATIC_URL }}css/filename.min.css.gz">

However on development I want the normal css file served (that way I don't have to re-minify and gzip each time I save) with:

  <link rel="stylesheet" href="{{ STATIC_URL }}css/filename.css">

Is there any way to achieve and automatize this behaviour by adding something to the deployer?, is there some other work-around (I could get rid of the .min extension if it's possible to add the .gz in a clean way?

I want to note the I know I could implement some html-parser which adds it on each deploy but I'm looking for a neat and django oriented solution.

Upvotes: 4

Views: 575

Answers (3)

Vladir Parrado Cruz
Vladir Parrado Cruz

Reputation: 2359

I like the @Nursultan idea. To enforce this you could code a context processor like this:

# On yourapp.context_processor.py
from django.conf import settings

def debug_set(request):
    return {'debug_set': settings.DEBUG}

# On your settings.py
TEMPLATE_CONTEXT_PROCESSORS = (
    .
    .
    .
    'yourapp.context_processors.debug_set',
)

# On your templates
{% if debug_set %}
    <link rel="stylesheet" href="{{ STATIC_URL }}css/filename.css">
{% else %}
    <link rel="stylesheet" href="{{ STATIC_URL }}css/filename.min.css.gz">
{% endif %}

Upvotes: 3

Nursultan Zarlyk
Nursultan Zarlyk

Reputation: 412

I have never met this problem, but I come up with these two solutions:

  1. Use different settings.py for production and development. But it requires to have the same names for *.min.js and change minifier's configuration.
  2. Or use a global variable and write everywhere

    {% if development_stage %} <link> {% else %} <link> {% endif %}

Django - How to make a variable available to all templates?

Upvotes: 0

FlipperPA
FlipperPA

Reputation: 14311

As usual, there's a Django package for that! There are two I use:

django-compressor: http://django-compressor.readthedocs.org/en/latest/ django-pipeline: https://django-pipeline.readthedocs.org/en/latest/

I started on django-pipeline but have moved to using compressor as of late. See the docs, I believe one will be what you're looking for. Good luck!

Upvotes: 1

Related Questions