Created
November 30, 2011 10:14
-
-
Save jeanphix/1408574 to your computer and use it in GitHub Desktop.
Django global user
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# middlewares.py | |
import threading | |
_thread_locals = threading.local() | |
def get_current_user(): | |
"""Returns the current user.""" | |
return getattr(_thread_locals, 'user', None) | |
class GlobalUserMiddleware(object): | |
"""Puts the current user in thread_locals.""" | |
def process_request(self, request): | |
_thread_locals.user = getattr(request, 'user', None) | |
# models.py | |
from middlewares import get_current_user | |
MyClass(models.Model): | |
created_by = models.ForeignKey(User, null=True, blank=True, | |
default=lambda: get_current_user()) |
Hum ok... I see.
Mozilla uses this trick too, to do the same thing for its commonware logger.
Good luck.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@thoas The need here is just to log which user created or updated the object (for many models) in both frontend and admin...
You both are right, I have no time for that (/budget) but I think I'll move to more qualitative things...