I want to get the currently logged in user (request.user) in the save method of models.py. I want to check the role of the user and see if it can p
I found a way to do that, it involves declaring a MiddleWare, though. Create a file called get_username.py inside your app, with this content:
from threading import current_thread
_requests = {}
def get_username():
t = current_thread()
if t not in _requests:
return None
return _requests[t]
class RequestMiddleware(object):
def process_request(self, request):
_requests[current_thread()] = request
Edit your settings.py and add it to the MIDDLEWARE_CLASSES:
MIDDLEWARE_CLASSES = (
...
'yourapp.get_username.RequestMiddleware',
)
Now, in your save() method, you can get the current username like this:
from get_username import get_username
...
def save(self, *args, **kwargs):
req = get_username()
print "Your username is: %s" % (req.user)