Skip to content

Instantly share code, notes, and snippets.

@Verurteilt
Created June 24, 2014 17:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Verurteilt/6ffaa97865c568f351a6 to your computer and use it in GitHub Desktop.
Save Verurteilt/6ffaa97865c568f351a6 to your computer and use it in GitHub Desktop.
from django.db.models.signals import pre_delete, post_save
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_request_atributos():
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
request = arg_dict.get(k)
break
del arg_dict
del arginfo
if(user):
break
usuario = Usuario.objects.get(usuario=user)
return usuario, path, request
except Exception as e:
print e
pass
from reversion.admin import VersionAdmin
from reversion.models import Version, Revision
import json
def _compare(obj1, obj2, excluded_keys):
d1, d2 = obj1.__dict__, obj2.__dict__
old, new = {}, {}
for k,v in d1.items():
if k in excluded_keys:
continue
try:
if v != d2[k]:
old.update({k: v})
new.update({k: d2[k]})
except KeyError:
old.update({k: v})
return old, new
def compare(obj1, obj2):
excluded_keys = 'object', 'object_id_int', '_state'
return _compare(obj1, obj2, excluded_keys)
@receiver(post_save)
def log(sender,instance,**kwargs):
try:
post_save.disconnect(log)
flag = CHANGE
usuario, path, request= obtener_request_atributos()
if not "admin" in path:
if instance._state.adding:
flag = ADDITION
try:
if flag == CHANGE:
# 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=CHANGE,
# change_message = "Modificado por %s" %force_text(usuario)
# )
VersionAdmin(LogEntry, "").log_change(request, instance, "Modificado s")
versiones = Version.objects.filter(content_type=get_content_type_for_model(instance)).order_by('-id')
version_nueva = versiones[0]
version_antigua = versiones[1]
compares = compare(version_antigua, version_nueva)
model_antiguo = compares[0]
model_nuevo = compares[1]
revision = Revision.objects.get(id=model_nuevo['id'])
cambiados = []
if(len(model_antiguo.keys()) == 2) and (len(model_nuevo.keys()) == 2):
if model_antiguo.keys()[0] == model_nuevo.keys()[0]:
revision.comment = "No se Modifico nada"
else:
for ca, va in json.loads(model_antiguo['serialized_data'])[0]['fields'].iteritems():
for cn,vn in json.loads(model_nuevo['serialized_data'])[0]['fields'].iteritems():
if ca == cn:
if va != vn:
cambiados.append(str(cn))
modificados = ', '.join(cambiados)
revision.comment = "Modificados: " + modificados
revision.save()
elif flag == ADDITION:
# 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
# )
VersionAdmin(LogEntry, "").log_addition(request, instance)
except Exception as e:
print e
pass
post_save.connect(log)
except Exception as e:
print e
pass
@receiver(pre_delete)
def log_delete(sender,instance,**kwargs):
try:
pre_delete.disconnect(log_delete)
flag = DELETION
usuario, path, request= obtener_request_atributos()
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