1

I have a global pre_save signal where I need to get the current logged in user i.e request.user.

I have tried the following which seems to work however, it looks like a bad idea...

@receiver(pre_save)
def my_handler(sender, **kwargs):
    import inspect

    for frame_record in inspect.stack():
        if frame_record[3] == 'get_response':
            request = frame_record[0].f_locals['request']
            break
        else:
            request = None
    print(request.user) <--- correct user is given

Are there any potential issues with above? Is there a better way to achieve this?

Using Python 3.4 and Django 1.8.4

Prometheus
  • 32,405
  • 54
  • 166
  • 302

1 Answers1

4

I think middleware will be better solution. Check this project to get the idea django-cuser.

btw. Inspecting stack to get the request is brilliant example of how can python be abused and still solve problems :)

beezz
  • 2,398
  • 19
  • 15