2

What I'm trying to do is, when user uploaded the CSV file. I'm trying to do functionalities in pandas.

Django template

<form action="{% url 'upload-timeslot' %}" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    Select image to upload:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload Image" name="submit">
</form>

My view

def bulk_timeslot_upload(request):
    if request.FILES:
        import pandas as pd
        csv = request.FILES['fileToUpload']
        data = pd.read_csv(csv)
        print(data)
    return render(request, 'bulk-timeslot.html')

when i tried to read csv, running server getting exited. If I import pandas globally, server not even running.

2 Answers2

2

I had the same issue and what helped me was this answer. (More info in Django docs)

In views.py

def import_csv(request):
    if request.method == 'POST':
        form = ImportFileForm(request.POST, request.FILES)
        if form.is_valid():

            # the temporary_file_path() shows Dask where to find the file
            df_in = dd.read_csv(request.FILES['file_name'].temporary_file_path())

in settings.py

FILE_UPLOAD_HANDLERS = ['django.core.files.uploadhandler.TemporaryFileUploadHandler',]
pyjavo
  • 1,598
  • 2
  • 23
  • 41
-1

actually the read_csv() takes in file, but ur request.FILES['fileToUpload'] is the memorybuffer. So, 2 possible ways are either save the csv file in ur system and then read it by passing the whole path, or use :

  def bulk_timeslot_upload(request):
    if request.FILES:
       import pandas as pd
       csv = request.FILES['fileToUpload']
       data = pd.read_csv(csv.read())
       print(data)
  return render(request, 'bulk-timeslot.html')
Jax.ajay
  • 49
  • 8