Retrieve user names from session ID in Django errors

Django error emails on 500 errors are pretty useless if you’re the acting
customer support for the day. There’s absolutely not much besides a
session ID, to identify which user actually got that exception. Obviously
for a startup, that’s essential to reacho out to little customers we do
have, if for nothing else than to apologize. Anyways here’s a simple
little snippet that can help you figure out a user from a session id.
Note, that the user might not be logged in, in that case there’s not much
you can do.

def get_user_from_sessionid(sessionid):
       """
       ``sessionid`` - is the identifier for the users session. 
       You can also find it in the Http500 error messages on screen
       or via email.

       >>> get_user_from_sessionid('fd3479022d77794897e5b23f4d461bbf')
       """
       from django.contrib.sessions.models import Session
       from django.contrib.auth.models import User


       session = Session.objects.get(session_key=sessionid)
       uid = session.get_decoded().get('_auth_user_id')
       user = User.objects.get(pk=uid)

       return user.id, user.username, user.email

Links

There’s also a way to add the username to the error emails themselves, by overriding a process_exception on a middleware. You can read about it here

.