api.py 1.57 KB
from rest_framework import viewsets, mixins, status
from rest_framework.response import Response
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import action
from datetime import datetime

from .models import Edicto
from .serializer import EdictoSerializer
from .utils import contador


class EdictoViewSet(mixins.CreateModelMixin,
                    mixins.RetrieveModelMixin,
                    mixins.UpdateModelMixin,
                    mixins.DestroyModelMixin,
                    mixins.ListModelMixin,
                    viewsets.GenericViewSet):

    queryset = Edicto.objects.all().order_by('id')
    serializer_class = EdictoSerializer
    authentication_classes = [SessionAuthentication, BasicAuthentication]
    permission_classes = [IsAuthenticated]

    @action(detail=True, methods=['put', 'patch'])
    def custom_update(self, request):
        edicto = request.data.get('cuerpo_edicto')
        cantidad_palabras = contador(edicto)

        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save(cantidad_palabras=cantidad_palabras, fecha_actualizacion=datetime.now())

        return Response(serializer.data, status=status.HTTP_200_OK)

    def perform_create(self, serializer):
        edicto = self.request.data.get('cuerpo_edicto')
        cantidad_palabras = contador(edicto)
        serializer.save(cantidad_palabras=cantidad_palabras)