Passing file to function to parse
Question: I have an upload form that takes a file and sends it to a function to parse.
It is a CSV file and im using a DataField type to store it.

views.py

    
    
    def upload(request):
        # Handle file upload
        if request.method == 'POST':
            form = UploadForm(request.POST, request.FILES)
            if form.is_valid():
                newdoc = CSV(file=request.FILES['csvfile'])
                newdoc.save()
    
                # Send file to parser
                import fanduel.load_data
                fanduel.load_data.parse(newdoc.file, request.user)
    
                # Redirect to the document list after POST
                return HttpResponseRedirect(reverse('app.views.upload'))
        else:
            form = UploadForm()  # A empty, unbound form
    

load_data.py

    
    
    def parse(file, username):
        import csv
        dataReader = csv.reader(open(file), delimiter=',', quotechar='"')
    

forms.py

    
    
    # In forms.py...
    from django import forms
    
    class UploadForm(forms.Form):
        csvfile = forms.FileField(
            label='Select a CSV file',
        )
    

models.py

    
    
    class CSV(models.Model):
        file = models.FileField(upload_to='csv/')
    

traceback:

    
    
    Environment:
    
    
    Request Method: POST
    Request URL: http://127.0.0.1:8000/app/
    
    Django Version: 1.7.6
    Python Version: 3.4.2
    Installed Applications:
    ('django.contrib.admin',
     'django.contrib.auth',
     'django.contrib.contenttypes',
     'django.contrib.sessions',
     'django.contrib.messages',
     'django.contrib.staticfiles',
     'import_export',
     'app')
    Installed Middleware:
    ('django.contrib.sessions.middleware.SessionMiddleware',
     'django.middleware.common.CommonMiddleware',
     'django.middleware.csrf.CsrfViewMiddleware',
     'django.contrib.auth.middleware.AuthenticationMiddleware',
     'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
     'django.contrib.messages.middleware.MessageMiddleware',
     'django.middleware.clickjacking.XFrameOptionsMiddleware')
    
    
    Traceback:
    File "C:\Users\Wilson\AppData\Roaming\Python\Python34\site-packages\django\core\handlers\base.py" in get_response
      111.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
    File "C:\Users\Wilson\PycharmProjects\bankroll2\app\views.py" in upload
      20.             app.load_data.parse(newdoc.file, request.user)
    File "C:\Users\Wilson\PycharmProjects\bankroll2\app\load_data.py" in parse
      13.     dataReader = csv.reader(open(file), delimiter=',', quotechar='"')
    
    Exception Type: TypeError at /app/
    Exception Value: invalid file: <FieldFile: csv/app_entry_history_20150316_w62ruKt.csv>
    

I'm not sure how to get it to pass it in as the correct file type. If I enter
a filepath manually into load_data.py it works fine, so it's something to do
with the way it's passed in.


Answer: I _think_ your problem is that you are trying to open the wrong filename. When
a file is uploaded to a webserver, it is either stored in memory, or written
to a temporary location - Django does this as well
(<https://docs.djangoproject.com/en/1.7/topics/http/file-uploads/#where-
uploaded-data-is-stored>).

So the value in `request.FILES['csv']` is the location of the temporary file.
What you want is the file that gets stored in your forms. You will need to
paste your forms and models, but I am guessing the following might work, so
instead of this

    
    
    newdoc = CSV(file=request.FILES['csvfile'])
    

you need

    
    
    newdoc = CSV(file=form.cleaned_data['csvfile'])
    

