Answer the question
In order to leave comments, you need to log in
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)
{
"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"
}
}
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)
{
"vendor_name": [
"This field is required."
],
"country": [
"This field is required."
]
}
Answer the question
In order to leave comments, you need to log in
The serializer VendorsSerializer
in the class CsvToDatabase
is 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 CsvToDatabase
capable 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 questionAsk a Question
731 491 924 answers to any question