0

I have a pandas script that takes in a CSV file, does some pandas stuff on it, and saves a new CSV file(or a response if we want that). The thing is that I want to be able to get that file in my django views.py file to be able to save it to the "converted file" database table. In short, I want to be able to store that file in a variable similar to

uploaded_file = request.FILES['upload-field']

I've tried various methods like returning the response but that just returns a string instead of an actual file.

Also, I should mention that all of this happens when the user POSTS the data (uploads a csv file)

here's my views.py

from .models import ConvertedDocument

def uploadView(request):
    if(request.method == 'POST'):
        uploaded_file = request.FILES['upload_field']

        generated_uid = get_random_string(16)
        generated_name = generated_uid+".csv"
        actual_name = uploaded_file.name
        
        # Block to save converted file
        converted_file = analysis(uploaded_file)

        converted_file.name = generated_name

        converted_document = ConvertedDocument()
        converted_document.file_uid = generated_uid
        converted_document.file_name = "converted_"+actual_name
        converted_document.file_size = converted_file.size
        converted_document.file_document = converted_file
        converted_document.uploaded_by = user
        converted_document.save()
        return redirect('upload')
    
    return render(request, 'functions/upload.html')

here's the save block from my analysis function

def analysis(file):
    upload_df = pd.read_csv (file)
    
    # pandas conversion code goes here...

    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename=category.csv'
    reuired_file_df.to_csv(path_or_buf=response)
    return response

What can I do so that the analysis() funtion returns a CSV file and not the data

  • Does this answer your question: https://stackoverflow.com/questions/35267585/django-pandas-to-http-response-download-file – Siva Sankar Jan 30 '21 at 18:47
  • @Siva Shankar No actually i've tried it but in my views file, it returns the HTTP response and not the file. I am looking for a way so that I can get the actual file – Atharva Malji Jan 31 '21 at 04:01

0 Answers0