I am using Django 2.1 and my project is ready for production. Is there a way that i can set settings.DEBUG == True only for superuser and show a default 500 internal server error for normal users. I have tried to write a middleware, but it seems not working. I do not want to use sentry(as recommended at many places). my middlewares.py is:
import sys
from django.views.debug import technical_500_response
from django.conf import settings
from django.contrib.auth import get_user_model
user = get_user_model() #I am using CustomUser model not Django user model
class UserBasedExceptionMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
return self.get_response(request)
def process_exception(self, request, exception):
if request.user.is_superuser:
return technical_500_response(request, *sys.exc_info())
I have also loaded my middleware in.
MIDDLEWARE = ['myproject.middlewares.UserBasedExceptionMiddleware',]
I have found a way to DEBUG application using development server without changing DEBUG. For this I made a debug_setting.py file (where my settings.py file is located).
In my debug_setting.py:
from .settings import *
DEBUG = True
Then in terminal using:
python manage.py runserver --settings=myproject.debug_setting 0.0.0.0:5000
We can see traceback of the error of our application without changing DEBUG=True for our production.
Update:
Alternatively we can also use django's Error Reporting system which would automatically mail 500 and 404 errros with the whole traceback to the mail addresses described in ADMINS = [] and MANAGERS = []. For this feature we need to smtp settings like EMAIL_HOST, EMIL_HOST_UESR, EMAIL_HOST_PASSWORD. Details are here https://docs.djangoproject.com/en/3.0/howto/error-reporting/