简体   繁体   中英

Switch on django error page only for admins when debug = False

It is a copy of: is there a way to show the Django debug stacktrace page to admin users even if DEBUG=False in settings? but there is no answer

How to show django error page with stacktrace when debug=False only for admin users. I don't want to use sentry.

I find an answer

In urls.py add

handler404 = 'site_utils.handler404'

Create site_utils.py in the same folder where urls.py and add there

from django.http import HttpResponseRedirect,  HttpResponsePermanentRedirect
import sys
from django.views.debug import technical_404_response, technical_500_response 
def handler404(request):
    if (request.user.is_active and request.user.is_staff) or request.user.is_superuser:
        exc_type, exc_value, tb = sys.exc_info()
        return technical_404_response(request, exc_value)
    else:
        return  HttpResponsePermanentRedirect("/")

What you are asking to do is incredibly insecure, which is likely why Django provides no default way to do this. Running DEBUG on a production app can expose your SETTINGS file (including API tokens) to the world.

If you really want to do this, take a look at django.views.debug.technical_500_response and write a custom exception handler that returns the value from there.

Here is a version for Django 3.2.

Save the following file in, for example, mysite/debug.py :

from django.utils.deprecation import MiddlewareMixin
from django.views.debug import technical_500_response
import sys

class UserBasedExceptionMiddleware(MiddlewareMixin):
    def process_exception(self, request, exception):
        if request.user.is_superuser:
            return technical_500_response(request, *sys.exc_info())

Update your mysite/settings.py as follows:

MIDDLEWARE_CLASSES = (
  ... whatever ...
  'mysite.debug.UserBasedExceptionMiddleware',
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM