Your Ad Here

Monday, January 2, 2012

Re: How to get current session user in models.py?

Hi,
I actually have already sent this to Shawn, but thought it might be useful if I post to it a broader audience. Here is my solution to this problem:

<code>
        user = None
        outer_frames = inspect.getouterframes(inspect.currentframe())
        for tpl in outer_frames:
            arginfo = inspect.getargvalues(tpl[0])
            if(type(arginfo[3]) is dict):
                arg_dict = arginfo[3].copy()
                for k in arg_dict:
                    if(type(arg_dict.get(k)) is WSGIRequest):
                        user = arg_dict.get(k).user
                        break
                del arg_dict
            del arginfo
            if(user):                
                break

</code>

This code is quite generic and should work in any place you ended up provided the origin was the django view/class method. I'm using it on models and customized admin forms for storing audit trails. It uses inspect to scan the parameters from the callers of the current frame stack. You can modify it to fish out pretty much anything.. there is no need to change the interfaces.

Hope it helps.

Cheers,
Waldek  

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/dzmUtcvpXrUJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

0 comments:

Post a Comment