Created
February 14, 2014 02:53
-
-
Save Verurteilt/8995007 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.db.models.signals import pre_save, pre_delete | |
from django.contrib.admin.models import LogEntry, DELETION, ADDITION, CHANGE | |
from django.utils.encoding import force_text | |
##Django admin | |
def get_content_type_for_model(obj): | |
return ContentType.objects.get_for_model(obj) | |
import inspect | |
from django.core.handlers.wsgi import WSGIRequest | |
#Encontrado en Google | |
def obtener_usuario_y_path_fuera_de_un_views(): | |
try: | |
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 | |
path = arg_dict.get(k).path | |
break | |
del arg_dict | |
del arginfo | |
if(user): | |
break | |
usuario = Usuario.objects.get(usuario=user) | |
return usuario, path | |
except: pass | |
@receiver(pre_save) | |
def log(sender,instance,**kwargs): | |
try: | |
pre_save.disconnect(log) | |
flag = CHANGE | |
usuario, path= obtener_usuario_y_path_fuera_de_un_views() | |
if not "admin" in path: | |
if instance._state.adding: | |
flag = ADDITION | |
try: | |
LogEntry.objects.log_action( | |
user_id=usuario.pk, | |
content_type_id=get_content_type_for_model(instance).pk, | |
object_id=instance.pk, | |
object_repr=force_text(instance), | |
action_flag=flag | |
) | |
except Exception as e: | |
print e | |
pre_save.connect(log) | |
except: pass | |
@receiver(pre_delete) | |
def log_delete(sender,instance,**kwargs): | |
try: | |
pre_delete.disconnect(log_delete) | |
flag = DELETION | |
usuario, path= obtener_usuario_y_path_fuera_de_un_views() | |
if not "admin" in path: | |
try: | |
LogEntry.objects.log_action( | |
user_id=usuario.pk, | |
content_type_id=get_content_type_for_model(instance).pk, | |
object_id=instance.pk, | |
object_repr=force_text(instance), | |
action_flag=flag | |
) | |
except Exception as e: | |
print e | |
pre_delete.connect(log_delete) | |
except: pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment