api.py 2.28 KB
from rest_framework import viewsets, filters, mixins, status
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import action
from django.utils import timezone

from .models import Edicto, Precio
from .serializer import EdictoSerializer, PrecioSerializer
from .filters import EdictoFilter, PrecioFilter
from .permissions import IsAdminOrAuthorized
from .utils import contador


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

    serializer_class = EdictoSerializer
    permission_classes = [IsAuthenticated, ]
    filter_backends = (DjangoFilterBackend, filters.OrderingFilter)
    filterset_class = EdictoFilter
    queryset = Edicto.objects.all()
    ordering_fields = ('fecha_creacion', 'id', 'estado')
    ordering = ('fecha_publicacion',)
    lookup_field = 'uuid'

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

    def partial_update(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)

        edicto = request.data.get('cuerpo_edicto')
        cantidad_palabras = contador(edicto)
        usuario = self.request.user

        serializer.save(cantidad_palabras=cantidad_palabras,
                        usuario_movimiento=usuario,
                        )

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


class PrecioViewSet(viewsets.ReadOnlyModelViewSet):
    serializer_class = PrecioSerializer
    permission_classes = [IsAuthenticated, IsAdminOrAuthorized]
    filter_backends = (DjangoFilterBackend, filters.OrderingFilter)
    filterset_class = PrecioFilter
    ordering_fields = ('usuario', )
    ordering = 'usuario'
    queryset = Precio.objects.all()