3

I'm trying to use catch the Django user in the Middleware but without success. Using Python 3.6 and Django 1.11.

from threading import local

_user = local()

class CurrentUserMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        _user.value = request.user
        return self.get_response(request)

def get_current_user():
    return _user.value

I need to save the request.user outside the class, in the get_current_user(), but it is not working.

Can someone give me a clue why I can't have the _user.value in the get_current_user() ?

The reason I'm doing this is to import to a model

from current_user import get_current_user

Thanks,

André
  • 24,706
  • 43
  • 121
  • 178
  • 1
    Why do you need to save the user as a thread-local variable outside of the `request` object? – Blender Feb 28 '18 at 19:01
  • I need to import the get_current_user to a model, "from current_user import get_current_user" – André Feb 28 '18 at 19:21
  • 1
    How does your model need to use the current user? Is there any reason why you cannot just pass the user object directly to the model? I'm asking because this seems like it's the wrong approach to whatever problem you're trying to solve. – Blender Feb 28 '18 at 19:26
  • I need to have the Django user in the model using this approach. – André Feb 28 '18 at 19:28
  • As Blender says, it's really unlikely you need to do this. What is your exact reason for wanting the user in the model, and why can't you just pass it when you need it? – Daniel Roseman Feb 28 '18 at 20:19
  • I need to have a simple way to get the user in the model. The app rely very much on the model and admin, and to get things simpler on the admin I need to do this. I know it is possible. – André Feb 28 '18 at 20:34
  • I understand, but your question is like asking, "what is the best rock to hit screws with?" It'll probably work, but it's not the right approach. What do you mean by *"`get_current_user()`, but it is not working."*? Does it throw an error? How do you use it? – Blender Mar 01 '18 at 00:12
  • See this https://stackoverflow.com/a/39313777/9262339 – Jekson Oct 05 '20 at 07:46

0 Answers0