Create a new file in your project folder (alongside urls.py) and name it middleware.py:

from __future__ import absolute_import, division, print_function

try:
    from threading import local
except ImportError:
    from django.utils._threading_local import local

_thread_locals = local()

def get_current_request():
    """ returns the request object for this thread """
    return getattr(_thread_locals, "request", None)

def get_current_user():
    """ returns the current user, if exist, otherwise returns None """
    request = get_current_request()
    if request:
        return getattr(request, "user", None)

class ThreadLocalMiddleware(object):
    """ Simple middleware that adds the request object in thread local stor    age."""

    def process_request(self, request):
        _thread_locals.request = request

    def process_response(self, request, response):
        if hasattr(_thread_locals, 'request'):
    del _thread_locals.request
        return response

Use the function get_current_user() anywhere you want by importing the middleware.

settings.py:

MIDDLEWARE = [
    ...
    'YOUR_PROJECT_NAME.middleware.ThreadLocalMiddleware',
]

models.py (example):

from YOUR_PROJECT_NAME.middleware import get_current_user

...

Class SomeModel(models.Model):
    ...

    def some_method(self):
        current_user = get_current_user()
        ....

I have tested this on Django 1.8.

Advertisement