J
J
Jekson2020-02-20 13:04:33
Django
Jekson, 2020-02-20 13:04:33

Error serializing json data?

The FileUploadView class accepts a .csv file and returns the parsed data as JSON (if I understand the usage correctly renderer_classes = [JSONRenderer])

class FileUploadView(APIView):
    parser_classes = ( MultiPartParser, FormParser)
    renderer_classes = [JSONRenderer]

    def put(self, request, format=None):
        if 'file' not in request.data:
            raise ParseError("Empty content")
        f = request.data['file']
        filename = f.name
        if filename.endswith('.csv'):
            file = default_storage.save(filename, f)
            r = csv_file_parser(file)
            status = 204
        else:
            status = 406
            r = "File format error"
        return Response(r, status=status)


The csv_file_parser() function, which is called in the class, validates the csv file and generates a dictionary. As a result, the result returned by the FileUploadView class

{
    "1": {
        "vendor_name": "Firstvendortestname",
        "country": "BE",
        "NDA date": "2019-12-24",
        "Primary Contact Name": "Jack Jhonson",
        "Primary Contact Email": "[email protected]",
        "Secondary Contact Name": "Jack2 Jhonson",
        "Secondary Contact Email": "[email protected]",
        "Modules": "Module1, Module2"
    },
    "2": {
        "vendor_name": "Firstvendortestname",
        "country": "BE",
        "NDA date": "",
        "Primary Contact Name": "Sandra Bullock",
        "Primary Contact Email": "[email protected]",
        "Secondary Contact Name": "Sandra Bullock",
        "Secondary Contact Email": "[email protected]",
        "Modules": "Module1, Module2"
    }
}


Further, this JSON is passed to the input of the CsvToDatabase class

class CsvToDatabase(APIView):

    def post(self, request, format=None):
        serializer = VendorsSerializer(data=request.data)
        print(request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


And when I call this code, I get an error

{
    "vendor_name": [
        "This field is required."
    ],
    "country": [
        "This field is required."
    ]
}


If I change the format of the input JSON to
{
"vendor_name": "Firstvendortestname",
"country": "BE",
"NDA date": "2019-12-24",
"Primary Contact Name": "Jack Jhonson",
"Primary Contact Email": "[email protected]",
"Secondary Contact Name": "Jack2 Jhonson",
"Secondary Contact Email": "[email protected]",
"Modules": "Module1, Module2"
}

That's OK . Tell me what to change so that my data is validated?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir, 2020-02-20
@Lepilov

The serializer VendorsSerializerin the class CsvToDatabaseis designed to receive data for one object, and you pass a list of objects to it. There are two options: either transfer each object from the front to the back with a separate request, or make it CsvToDatabasecapable of processing a list of objects.
In the first option, you will have no transactionality. That is, the first object can be saved, and the second one will not be saved if the connection or data curves are broken.
In the second option, you can first check all the objects, and only if successful, save them to the database. The start could be something like this:

class CsvToDatabase(APIView):
    def post(self, request, format=None):
        for key, data_item in request.data.items():
            serializer = VendorsSerializer(data=data_item)
            ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question