我正在使用Need a minimal Django file upload example
复制猫我用我的代码更改了view.py,将csv文件转储到sqlite数据库中。 我已经在默认的sqlite数据库中创建了表。
import sqlite3
import csv
import sys
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from myproject.myapp.models import Document
from myproject.myapp.forms import DocumentForm
def list(request):
# Handle file upload
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile = request.FILES['docfile'])
newdoc.save()
gfile= csv.reader(open(newdoc))
gon = sqlite3.connect("database.sqlite")
gon.text_factory = str
gon.execute("DELETE FROM abc where rowID > 0 ")
gon.executemany("insert into abc values (?, ?, ?, ?, ?)", gfile)
gon.commit()
gon.close()*
return HttpResponseRedirect(reverse('myproject.myapp.views.list'))
else:
form = DocumentForm() # A empty, unbound form
# Load documents for the list page
documents = Document.objects.all()
# Render list page with the documents and the form
return render_to_response(
'myapp/list.html',
{'documents': documents, 'form': form},
context_instance=RequestContext(request)
)
我的代码是从第一次引入gfile开始的
错误@第20行:强制转换为unicode:需要字符串或缓冲区,找不到文档 请帮忙
答案 0 :(得分:1)
您正在将Document
个实例传递给open
。相反,您应该传递直接上传到csv.reader
的文件:
gfile = csv.reader(request.FILES['docfile'])