tags:

views:

561

answers:

1

hi everyone!i try to upload a csv file into my web application and store it into mysql database but failed.Please can anyone help me?

my user.py script:

def import_contact(request):
if request.method == 'POST':
 form = UploadContactForm(request.POST, request.FILES)
 if form.is_valid():
  csvfile = request.FILES['file']
  print csvfile

  csvfile.read()
                    testReader = csv.reader(csvfile,delimiter=' ', quotechar='|')




  for row in testReader:
   print "|".join(row)
 return HttpResponseRedirect('/admin')

else:
 form = UploadContactForm()

vars = RequestContext(request, { 'form': form })
return render_to_response('admin/import_contact.html', vars)

my forms.py script:

class UploadContactForm(forms.Form):
file  = forms.FileField(label='File:', error_messages = {'required': 'File required'})
+1  A: 

Since you haven't provided the code for the getcsv function, I'll have to use my crystal ball here a bit.

One reason why the print in the for row in testReader: loop isn't working is that getcsv may already processes the file. Use the seek method to reset the objects position in the file to zero again. That way the for loop will process it properly.

Another reason why there's nothing stored in the database might be that in the code you've supplied there doesn't seem to be a reference to a model. So how should Django know what it should store and where?

Mark van Lent