Django – Add Username to 500 Error Reports

This information was taken from:

I have been building a Social Networking style website in Django and recently received multiple 500 error reports due to users not having proper variables set.  I found the default 500 error email to be rather lacking with clues as to which users were actually causing the 500 errors, so I used the snippet above to add the request.user.username and variables to 500 tracebacks for authenticated users.

Thanks to the Author Sid for a very useful piece of code.

To get this working, I created a new app called errorreporting, and pasted the following code into a file called inside the errorreporting folder:

class ExceptionUserInfoMiddleware(object):
Adds user details to request context on receiving an exception, so that they show up in the error emails.
Add to settings.MIDDLEWARE_CLASSES and keep it outermost(i.e. on top if possible). This allows
it to catch exceptions in other middlewares as well.

    def process_exception(self, request, exception):
Process the exception.

- `request`: request that caused the exception
- `exception`: actual exception being raised

            if request.user.is_authenticated():
                request.META['USERNAME'] = str(request.user.username)
                request.META['USER_EMAIL'] = str(

Then, in, I added the following line to the top of the MIDDLEWARE_CLASSES block:

This entry was posted in Django and tagged , , , , , . Bookmark the permalink.

Comments are closed.