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.
I’m getting an error trying to implement this —
django.core.exceptions.AppRegistryNotReady: Models aren’t loaded yet.
Do you know where the issue might be. I have the middleware.py file and I’m trying to use the function — user = get_current_user() — and it’s throwing the error.
Hello Michael,
I think this mostly caused when you use it outside function (executing in import time), try to use it inside your form/model method.
If that didn’t help, please post your code where you used the function (get_current_user()).
Thank you!
You’re welcome.
Can you elaborate on this?
” I think this mostly caused when you use it outside function (executing in import time), try to use it inside your form/model method. ”
I placed in my models folder as well as beside urls.py but still it is showing Name error that name ‘get_current_user’ is not defined.
Hello,
I just updated the post. Please see if that helps you.
Thank you for the code!
I have a problem the object function and I can’t get it to work. This is what I get.
File “C:\python36\lib\site-packages\django\core\handlers\base.py”, line 36, in load_middleware
mw_instance = middleware(handler)
TypeError: object() takes no parameters