Martín Miranda

Merge branch 'feature/#36_visibilizar_includes_y_filtros' into 'develop'

Feature/#36 visibilizar includes y filtros



See merge request !30
... ... @@ -5,4 +5,6 @@ from .models import Edicto, Precio
# Register your models here.
admin.site.register(Precio)
admin.site.register(Edicto)
... ...
from rest_framework import viewsets, filters, mixins, status, serializers
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
... ... @@ -7,9 +7,10 @@ from datetime import datetime
from .models import Edicto, Precio
from .serializer import EdictoSerializer, PrecioSerializer
from .filters import EdictoFilter
from .filters import EdictoFilter, PrecioFilter
from .pagination import CustomPagination
from .permissions import IsAdminOrAuthorized
from .utils import contador
# from .precio import contador
class EdictoViewSet(mixins.CreateModelMixin,
... ... @@ -24,13 +25,15 @@ class EdictoViewSet(mixins.CreateModelMixin,
filter_backends = (DjangoFilterBackend, filters.OrderingFilter)
filterset_class = EdictoFilter
queryset = Edicto.objects.all()
ordering_fields = ('usuario__usuario', 'estado', 'fecha_publicacion', 'id',)
ordering = 'id'
ordering_fields = ('usuario',)
ordering = 'usuario'
pagination_class = CustomPagination
def perform_create(self, serializer):
edicto = self.request.data.get('cuerpo_edicto')
cantidad_palabras = contador(edicto)
serializer.save(cantidad_palabras=cantidad_palabras, usuario=self.request.user)
usuario = self.request.user
serializer.save(cantidad_palabras=cantidad_palabras, usuario=usuario)
@action(detail=True, methods=['put', 'patch'])
def custom_update(self, request):
... ... @@ -45,26 +48,12 @@ class EdictoViewSet(mixins.CreateModelMixin,
return Response(serializer.data, status=status.HTTP_200_OK)
class PrecioViewSet(mixins.CreateModelMixin,
mixins.RetrieveModelMixin,
mixins.ListModelMixin,
viewsets.GenericViewSet):
queryset = Precio.objects.all().order_by('id')
class PrecioViewSet(viewsets.ReadOnlyModelViewSet):
serializer_class = PrecioSerializer
permission_classes = [IsAuthenticated, ]
def create(self, request, *args, **kwargs):
user = request.user
if not user.is_staff:
raise serializers.ValidationError("El usuario no es parte del personal designado.")
return super().create(request, *args, **kwargs)
def retrieve(self, request, *args, **kwargs):
instance = self.get_object()
serializer = self.get_serializer(instance)
data = serializer.data
data['id'] = instance.id
return Response(data)
permission_classes = [IsAuthenticated, IsAdminOrAuthorized]
filter_backends = (DjangoFilterBackend, filters.OrderingFilter)
filterset_class = PrecioFilter
ordering_fields = ('usuario', )
ordering = 'usuario'
queryset = Precio.objects.all()
pagination_class = CustomPagination
... ...
from django_filters import rest_framework as filters
from edicto.models import Edicto
from edicto.models import Edicto, Precio
class EdictoFilter(filters.FilterSet):
fecha_creacion__gte = filters.DateFilter(field_name="fecha_creacion", lookup_expr='gte', label='Desde')
fecha_creacion__lte = filters.DateFilter(field_name="fecha_creacion", lookup_expr='lte', label='Hasta')
class Meta:
model = Edicto
fields = ('usuario', 'estado', 'fecha_publicacion', 'id',)
fields = {'usuario': ['exact'],
'estado': ['exact'],
'id': ['exact'],
}
class PrecioFilter(filters.FilterSet):
class Meta:
model = Precio
fields = {
'usuario': ['exact'],
'precio': ['exact'],
'vigencia_desde': ['exact'],
'vigencia_hasta': ['exact'],
'moneda': ['exact'],
}
... ...
from rest_framework.pagination import PageNumberPagination
class CustomPagination(PageNumberPagination):
page_size = 2
page_size_query_param = 'page_size'
max_page_size = 1000
... ...
from rest_framework import permissions
class IsAdminOrAuthorized(permissions.BasePermission):
def has_permission(self, request, view):
return request.user.is_staff or request.user.is_authenticated or request.user.is_authorized
... ...
from rest_framework import serializers
from .constants import EXTENSIONES_VALIDAS
from .models import Edicto, Precio, ComprobantePago
from usuario.serializers import UsuarioSerializer
from .models import Edicto, Precio
from usuario.serializers import UsuarioListaSerializer
class EdictoSerializer(serializers.ModelSerializer):
included_serializers = {
'usuario': UsuarioListaSerializer,
}
class Meta:
model = Edicto
... ... @@ -21,11 +25,8 @@ class EdictoSerializer(serializers.ModelSerializer):
'fecha_creacion',
'observaciones',
'fecha_publicacion',
)
included_serializers = {
'usuario': 'username.serializers.UsuarioListaSerializer',
}
)
read_only_fields = ('usuario', 'fecha_publicacion', 'cantidad_palabras', 'fecha_creacion')
... ... @@ -45,7 +46,6 @@ class EdictoSerializer(serializers.ModelSerializer):
class PrecioSerializer(serializers.ModelSerializer):
usuario = UsuarioSerializer()
class Meta:
model = Precio
... ... @@ -57,12 +57,6 @@ class PrecioSerializer(serializers.ModelSerializer):
'vigencia_hasta',
)
def validate(self, data):
request = self.context.get('request')
user = request.user if request else None
if not user or user.is_anonymous:
raise serializers.ValidationError("El usuario debe estar autenticado.")
if not user.is_staff:
raise serializers.ValidationError("El usuario no es parte del personal designado.")
return data
included_serializers = {
'usuario': UsuarioListaSerializer
}
\ No newline at end of file
... ...
... ... @@ -3,8 +3,7 @@ import re
def contador(edicto):
expresiones = re.findall(r'\(\.\.\.', edicto)
texto = edicto.split()
cantidad_palabras = len(texto)
cantidad_expresiones = len(expresiones)
total_edicto = cantidad_palabras + cantidad_expresiones
return total_edicto
edicto_sin_guiones = re.sub(r'(?<!\w)-|-(?!\w)', ' ', edicto)
palabras = re.split(r'\s+', edicto_sin_guiones)
total_palabras = len(palabras) + len(expresiones)
return total_palabras
... ...
... ... @@ -48,6 +48,7 @@ DJANGO_APPS = (
THIRD_PARTY_APPS = (
'rest_framework',
'rest_framework_json_api',
'django_filters',
'corsheaders',
'oauth2_provider',
... ... @@ -157,9 +158,24 @@ REST_FRAMEWORK = {
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
),
'DEFAULT_RENDERER_CLASSES': ('rest_framework_json_api.renderers.JSONRenderer',),
'DEFAULT_RENDERER_CLASSES': (
'rest_framework_json_api.renderers.JSONRenderer',
'rest_framework_json_api.renderers.BrowsableAPIRenderer'
),
'DEFAULT_METADATA_CLASS': 'rest_framework_json_api.metadata.JSONAPIMetadata',
'NON_FIELD_ERRORS_KEY': 'error_messages'
'DEFAULT_FILTER_BACKENDS': (
'rest_framework_json_api.filters.QueryParameterValidationFilter',
'rest_framework_json_api.filters.OrderingFilter',
'rest_framework_json_api.django_filters.DjangoFilterBackend',
'rest_framework.filters.SearchFilter',
),
'SEARCH_PARAM': 'filter[search]',
'TEST_REQUEST_RENDERER_CLASSES': (
'rest_framework_json_api.renderers.JSONRenderer',
),
'TEST_REQUEST_DEFAULT_FORMAT': 'vnd.api+json',
}
ACTIVAR_HERRAMIENTAS_DEBUGGING = env.bool('ACTIVAR_HERRAMIENTAS_DEBUGGING', default=True)
... ...