使用上下文處理器訪問模板中的 settings.DEBUG

in myapp/context_processors.py:

from django.conf import settings

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

in settings.py:

TEMPLATES = [
    {
        ...
        'OPTIONS': {
            'context_processors': [
                ...
                'myapp.context_processors.debug',
            ],
        },
    },
]

或者,對於版本<1.9:

TEMPLATE_CONTEXT_PROCESSORS = (
    ...
    'myapp.context_processors.debug',
)

然後在我的模板中,簡單地說:

 {% if DEBUG %} .header { background:#f00; } {% endif %}
 {{ DEBUG }}