Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to implement debug-only middleware in django

I have a middleware class that appends a comment block to HTML/XML templates which identifies the template location, the view that called it and its arguments and so on. Obviously I don't want to display this comment block in production. The middleware class itself has a

if settings.DEBUG:
    # write to template here

caveat, so it should not write to the template if debug mode is on, but for my own piece of mind I'd rather not add the middleware class at all on the production server. I'd like to be able to add it to the middleware classes only in my local settings file, but as it is a tuple obviously that's not possible. I could just override the MIDDLEWARE_CLASSES in my local settings but before I do that I was wondering if there was a more accepted/neater way of doing this.

like image 270
Pete Tinkler Avatar asked Dec 02 '25 09:12

Pete Tinkler


1 Answers

You should split your production and local settings to different files, then in your local settings you would just add your middleware. Small example to get you started:

File structure:

Settings
---> __init__.py
---> prod.py
---> dev.py

Example how to add django_debug_toolbar only in dev.py settings:

__init__.py:

# Other settings ommitted
MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)

dev.py:

from settings import *
# Other settings ommitted
MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware',)
like image 134
matino Avatar answered Dec 04 '25 00:12

matino



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!