mixins.py
2.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
from typing import Optional
from actstream import action
from actstream.models import Action
from django.contrib.contenttypes.models import ContentType
from rest_framework.response import Response
from rest_framework import status
from core.constants import iniciado
from core.serializers import ActionSerializer
# class FiltroObligatorioMixin(object):
# nombre_filtro_obligatorio: Optional[str] = None
#
# def get_queryset(self):
# queryset = super().get_queryset()
#
# if not self.action == 'list':
# return queryset
#
# # en el caso de que la accion sea listar, controlar que vengan los datos del filtro indicado
# filtro = self.request.GET.get(self.get_nombre_filtro_obligatorio(), None)
# if filtro:
# return queryset
#
# return queryset.none()
#
# def get_nombre_filtro_obligatorio(self):
# assert self.nombre_filtro_obligatorio is not None, (
# "Debe definir el atributo nombre_filtro_obligatorio a la clase '%s'"
# % self.__class__.__name__
# )
#
# return self.nombre_filtro_obligatorio
class AuditoriaMixin:
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
action_object = serializer.instance
self.registrar_accion(usuario=self.request.user, verb=iniciado, instance=serializer.instance,
data=serializer.data)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
def perform_update(self, serializer):
serializer_modificado = self.get_serializer(data=self.request.data)
serializer_modificado.is_valid()
serializer_accion = self.get_serializer(instance=serializer.instance)
data = {'data_inicial': serializer_accion.data, 'data_modificada': serializer_modificado.data}
self.registrar_accion(usuario=self.request.user, verb=serializer_modificado.data["estado"], instance=serializer.instance,
data=data)
serializer.save()
@staticmethod
def registrar_accion(usuario, verb, instance, data=None, target=None):
action.send(usuario, verb=verb, action_object=instance, target=target, data=data)
@staticmethod
def obtener_historial_acciones(content_type, action_objects_id, request):
content_type = ContentType.objects.get(model=content_type)
historial_actividades = Action.objects.filter(
action_object_object_id__in=action_objects_id,
action_object_content_type_id=content_type.id
)
serializer = ActionSerializer(historial_actividades, many=True, context={'request': request})
return serializer