0

I am trying to upload a CSV file to a Django model. Here is the code i have been trying for it to work:

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')

The problem is that i have tried to remove and add the above commented lines for somehow check if the code works.But it is throwing different types of errors for different lines. currently it is throwing the error:

expected str, bytes or os.PathLike object, not InMemoryUploadedFile

Kindly tell what might be the issue? Thanks.

1
  • you need to save it somewhere if you want to open it as a file Commented Apr 5, 2023 at 5:56

1 Answer 1

0

Joran Beasley answer is correct. Here is my updated code:

    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:
            ...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.