简体   繁体   中英

Unable to upload CSV file using Python/Django

I am trying to upload the csv file using Django and planning to parse the CSV file. But this code fails to upload the file and keeps going to the else condition. What is wrong with this code? Thanks!

from django.shortcuts import render
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse

import csv
import codecs

from items.models import UploadFileForm


def handle_files(f):
    reader = csv.DictReader(open(f))
    for row in reader:
    print row

def home(request):
    if request.method == "POST":
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            handle_files(request.FILES['file'])
            return HttpResponseRedirect('/workflow/')
        else:
            print form.errors
            print request.FILES
            return HttpResponseRedirect('/workflow/upload')

    else:
        form = UploadFileForm()
        return render(request, 'template.html', {'formset': form})

template.html

<form action="" method="post" enctype="multipart/form-data">{% csrf_token %}

   <input type="file" name="csv_file" />
   <input type="submit" value="Upload" />

</form>

forms.py

from django import forms

class UploadFileForm(forms.Form):
    title = forms.CharField(max_length=100)
    file = forms.FileField()

Instead you can try(You don't need to check whether form is valid unless u have validation enabled):

def home(request):
    if request.method == "POST":
        if request.FILES:
            handle_files(request.FILES['file'])
            return HttpResponseRedirect('/workflow/')
        else:
            return HttpResponseRedirect('/workflow/upload')

    else:
        form = UploadFileForm()
        return render(request, 'template.html', {'formset': form})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM