1

I'm using Django to host a web application, and I would like to obtain a CSV file from the user, and process this information (using Python). I am currently using this line of code in the HTML to obtain the CSV file:

<input type="file" accept="text/csv" id="mycsv">

Where in the Django project should I obtain the information from the CSV file, and how would I go about doing this? (I know the question is broad and doesn't give context for my specific project, but I figure that once I know how to access the data in the CSV I can figure the rest out).

  • Possible duplicate of [Need a minimal Django file upload example](https://stackoverflow.com/questions/5871730/need-a-minimal-django-file-upload-example) – Loïc Jul 06 '17 at 19:29
  • Doesn't address my specific desire to use python with the data once I've figured out how to get the csv file. – user7518095 Jul 06 '17 at 19:34
  • I've never done it so I'll just leave it as a comment, but looking at the documentation for [File Uploads](https://docs.djangoproject.com/en/1.11/topics/http/file-uploads/) it seems you should be able to access and manipulate the data request.FILES without saving the files to disk. – Paulo Almeida Jul 06 '17 at 20:47
  • So if I understand correctly you have created some models, and would like to parse the css file to populate those models? – dentemm Jul 07 '17 at 06:45

2 Answers2

1

Files uploaded by the user will go to the media folder that you have defined in your settings.py file.

You should be able to access user uploaded files in the media directory from your python code with something like this:

file_ = open(os.path.join(settings.MEDIA_ROOT, 'name_of_file'))

More info on MEDIA_ROOT and MEDIA_URL can be found here.

King Leon
  • 1,154
  • 12
  • 21
  • What if I don't want to have permanent access to the file? When using the website, I want the user to 1) upload the CSV, 2) have the website automatically parse data from it, and 3) have the website automatically update a database accordingly. Once steps 1-3 are done, I do not want to keep track of the file (I don't want it stored in media). – user7518095 Jul 06 '17 at 20:35
  • After processing the file, you should be able to delete it using something like this `os.remove(os.path.join(settings.MEDIA_ROOT, "name_of_file"))` – King Leon Jul 06 '17 at 20:42
1

Step 1: upload the file

# forms.py
from django import forms

class UploadFileForm(forms.Form):
    file  = forms.FileField()

Step 2: parse data and update database

# views.py
import csv

from .models import YourModel

def myview(request):
    if request.method == "POST":    
        form = UploadFileForm(request.POST, request.FILES)

        if form.is_valid():
            reader = csv.reader(form.cleaned_data['file'])

            for row in reader:
                try:
                    some_instance = YourModel.objects.get_or_create(row[...])

            ... 
dentemm
  • 6,231
  • 3
  • 31
  • 43