Skip to content

Instantly share code, notes, and snippets.

@jeanphix
Created November 30, 2011 10:14
Show Gist options
  • Select an option

  • Save jeanphix/1408574 to your computer and use it in GitHub Desktop.

Select an option

Save jeanphix/1408574 to your computer and use it in GitHub Desktop.
Django global user
# 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())
@thoas

thoas commented Nov 30, 2011

Copy link
Copy Markdown

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