Django Development Server with DEBUG=False

When you run the Django development server with DEBUG=True, static files are served from their location before collectstatic is run. This is what you want because changes you make are immediately reflected in your pages. Also all hosts are allowed.

Of course you would never run in production with DEBUG=True. This means your development system is not a very good replica of the production system when it comes to static files. If you are having problems with static files, it would be nice if you could work on them in development. It turns out you can. Just run:

python manage.py runserver --insecure

You also will need to setup a local directory for collectstatic to write to:

MEDIA_ROOT = 'my local media root'
STATIC_ROOT = 'my local static root'

then run collectstatic. In my case, I also needed to turn off django-pipeline.

Advertisements

Variables in Django Static Tags

The Django staticfiles app is great for getting your static files working both in development in production. One feature the documentation is not clear on is the use of context variables inside static tags. Lets say you have a context variable named “MY_PROJECT” and you try to do the following in a template:

{% load staticfiles %}
<link href="{% static 'css/{{ MY_PROJECT }}.css' %}" rel="stylesheet">

This works when DEBUG=True, but causes mysterious HTTP 500 errors when DEBUG=False.

The way to accomplish this is to make a new context variable in your views (or context processor), like:

MY_PROJECT_CSS = 'css/{}.css'.format(MY_PROJECT)

Then change your template to:

{% load staticfiles %}
 <link href="{% static MY_PROJECT_CSS|safe %}" rel="stylesheet">

Don’t forget the |safe filter, or you will get some strange errors.