Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing the user's request in a post_save signal

I have done the below post_save signal in my project.

from django.db.models.signals import post_save from django.contrib.auth.models import User  # CORE - SIGNALS # Core Signals will operate based on post  def after_save_handler_attr_audit_obj(sender, **kwargs):     print User.get_profile()      if hasattr(kwargs['instance'], 'audit_obj'):         if kwargs['created']:             kwargs['instance'].audit_obj.create(operation="INSERT", operation_by=**USER.ID**).save()         else:             kwargs['instance'].audit_obj.create(operation="UPDATE").save()   # Connect the handler with the post save signal - Django 1.2 post_save.connect(after_save_handler_attr_audit_obj, dispatch_uid="core.models.audit.new") 

The operation_by column, I want to get the user_id and store it. Any idea how can do that?

like image 624
Mo J. Mughrabi Avatar asked Jan 17 '11 18:01

Mo J. Mughrabi


2 Answers

Can't be done. The current user is only available via the request, which is not available when using purely model functionality. Access the user in the view somehow.

like image 94
Ignacio Vazquez-Abrams Avatar answered Oct 12 '22 12:10

Ignacio Vazquez-Abrams


I was able to do it by inspecting the stack and looking for the view then looking at the local variables for the view to get the request. It feels like a bit of a hack, but it worked.

import inspect, os  @receiver(post_save, sender=MyModel) def get_user_in_signal(sender, **kwargs):     for entry in reversed(inspect.stack()):         if os.path.dirname(__file__) + '/views.py' == entry[1]:             try:                 user = entry[0].f_locals['request'].user             except:                 user = None             break     if user:         # do stuff with the user variable 
like image 45
PaulR Avatar answered Oct 12 '22 10:10

PaulR