我试图上传一个CSV文件到Django模型。这是我一直在努力工作的代码:
def post(self, request):
if(request.method=='POST'):
# csv_file=request.FILES.get('file')
csv_file = request.FILES['file']
Error---->with open(csv_file, 'r') as csvfile:
# reader=csv_file.read().decode("utf-8")
# reader=TimeSeries.import_data(data = open(csv_file))
# reader = csv.reader(csv_file.read().decode('utf-8').splitlines())
reader = csv.reader(csvfile)
print("here3")
print (reader);
for row in reader:
print("here4")
print(row)
queryset = Station.objects.all()
print("here5")
# serializer_class = TimeSeriesSerializer
queryset = queryset.filter(name=row['Station Name'])
TimeSeriesInstance=TimeSeries(station=queryset.number,date=row['Date'],hour=row['Time'],value=row['Value'])
TimeSeriesInstance.save()
# process_file.delay(csv_file)
return HttpResponse('Success')
问题是,我试图删除并添加上述注释行,以某种方式检查代码是否有效。但是它会为不同的行抛出不同类型的错误。当前抛出错误:
期望的str、bytes或os。PathLike对象,而不是InMemoryUploadedFile
请告诉我可能是什么问题?谢谢。
Joran Beasley回答正确。下面是我更新后的代码:
def post(self, request):
if(request.method=='POST'):
csv_file = request.FILES['file']
file_name = default_storage.save(csv_file.name, csv_file)
csvfile = default_storage.open(file_name, 'r')
reader = csv.reader(csvfile)
next(reader)#skipping the header row
for row in reader:
...