diff --git a/.gitignore b/.gitignore index 7ef953a7..52b414e8 100644 --- a/.gitignore +++ b/.gitignore @@ -177,3 +177,5 @@ static __pycache__ .env.test + +media diff --git a/prizetap/serializers.py b/prizetap/serializers.py index 606504d6..4a369301 100644 --- a/prizetap/serializers.py +++ b/prizetap/serializers.py @@ -1,11 +1,13 @@ import base64 import json +from django.core.validators import FileExtensionValidator from rest_framework import serializers from authentication.serializers import SimpleProfilerSerializer from core.constraints import ConstraintVerification, get_constraint from core.serializers import ChainSerializer, UserConstraintBaseSerializer +from core.utils import UploadFileStorage from .constants import CONTRACT_ADDRESSES from .models import Constraint, LineaRaffleEntries, Raffle, RaffleEntry, UserConstraint @@ -94,6 +96,13 @@ class Meta: class CreateRaffleSerializer(serializers.ModelSerializer): + constraint_files = serializers.ListField( + required=False, + child=serializers.FileField( + allow_empty_file=False, validators=[FileExtensionValidator(["csv"])] + ), + ) + class Meta: model = Raffle fields = "__all__" @@ -124,6 +133,7 @@ def validate(self, data): if len(constraint_class.param_keys()) != 0: constraint_class.is_valid_param_keys(constraint_params[c.name]) except KeyError as e: + # TODO: revise errors raise serializers.ValidationError( {"constraint_params": [{f"{c.name}": str(e)}]} ) @@ -156,6 +166,22 @@ def validate(self, data): data["creator_profile"] = self.context["user_profile"] return data + def create(self, validated_data): + if "constraint_files" in validated_data: + constraint_files = validated_data.pop("constraint_files") + constraint_params = json.loads(validated_data.get("constraint_params")) + file_storage = UploadFileStorage() + for key, constraint in constraint_params.items(): + if "CSV_FILE" not in constraint: + continue + for file in constraint_files: + if constraint["CSV_FILE"] == file.name: + path = file_storage.save(file) + constraint["CSV_FILE"] = path + break + validated_data["constraint_params"] = json.dumps(constraint_params) + return super().create(validated_data) + class RaffleSerializer(serializers.ModelSerializer): chain = ChainSerializer() diff --git a/prizetap/views.py b/prizetap/views.py index 4d734daa..d87a46cd 100644 --- a/prizetap/views.py +++ b/prizetap/views.py @@ -4,6 +4,7 @@ from django.shortcuts import get_object_or_404 from django.utils import timezone from rest_framework.generics import CreateAPIView, ListAPIView, RetrieveAPIView +from rest_framework.parsers import FormParser, MultiPartParser from rest_framework.permissions import IsAuthenticated from rest_framework.request import Request from rest_framework.response import Response @@ -195,6 +196,7 @@ def get(self, request, raffle_pk): class CreateRaffleView(CreateAPIView): + parser_classes = (MultiPartParser, FormParser) permission_classes = [IsAuthenticated] serializer_class = CreateRaffleSerializer