Last update on .

Credit: Haki Benita, 07-Jun-2017, 5 Ways to Make Django Admin Safer
Credit: Haki Benita, 07-Jun-2017, 5 Ways to Make Django Admin Safer

Using colors to distinguish different environments or databases has always been a nice way to make sure you are working in the right place. This article explains how to use that trick to keep you production and development environments visually distinct.

Often we work in multiple environments at the same time. We may be making updates in one environment or database while another is running a task for us in the background. I have always used different background colors in my terminal windows to help me keep straight on where I was working within my organizational systems.

I came across this article from Haki Benita that shows how to add a color bar at the top of the Django Admin to indicate which environment you are actually working in. This comes in handy when you are making updates to your code locally, but are also using the production environment as a reference by helping you keep straight on which one you are in at the time. Any help we can get on reducing mistakes is welcome!

Here's how you can visually distinguish between your different Django project environments:

First you need to have some way of knowing which environment you are on. We need to set up a variable called ENVIRONMENT_NAME that is populated during deployment. We will use another variable called ENVIRONMENT_COLOR for the indicator color. You can set the color to whatever works best for you.

To add the environment indicator to every page in the admin, override the base admin template:

# app/templates/admin/base_site.html

{% extends “admin/base_site.html” %}

{% block extrastyle %}

<style type=”text/css”>
    body:before {
        display: block;
        line-height: 35px;
        text-align: center;
        font-weight: bold;
        text-transform: uppercase;
        color: white;
        content: “{{ ENVIRONMENT_NAME }}”;
        background-color: {{ ENVIRONMENT_COLOR }};
    }
</style>

{% endblock %}

To make the ENVIRONMENT variables from settings.py available in the template we use a context processor:

# app/context_processors.py

from django.conf import settings

def from_settings(request):
    return {
        'ENVIRONMENT_NAME': settings.ENVIRONMENT_NAME,
        'ENVIRONMENT_COLOR': settings.ENVIRONMENT_COLOR,
    }

To register the context processor add the following in your base settings.py file:

TEMPLATES = [{
    …
    'OPTIONS': {
        'context_processors': [
            …
            'app.context_processors.from_settings',
        ],
    …
    },
}]

Now when you open Django Admin you should see the indicator on top as shown below. (Remember, you can customize the color to fit your preferences.)

django.admin.colorized.png

Additional Information about Entry

Comments

No comments yet.

Post your comment