python - Django 执行 Python 脚本

标签 python django csv

我正在用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:需要字符串或缓冲区,找到文档 请帮忙

最佳答案

您正在将 Document 实例传递给 open。相反,您应该传递直接上传到 csv.reader 的文件:

gfile = csv.reader(request.FILES['docfile'])

关于python - Django 执行 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18938453/

相关文章:

python - 在python 3中处理mysql结果

django - 为什么 django inspectdb 会跳过一些 id?

python - django.db.models.fields.Field.name 参数的目的

R cbind 数据帧彼此相邻,无需公共(public) key

python - 从 1904 年开始以秒为单位转换时间

python - 如何动态创建 PyQt 属性

python - 获得 kolmogorov-smirnov 检验所需的临界值

python - 使用unittest django测试存储在内存中的csv文件

sql-server - 从 SSIS 中的 CSV 导入 yyyyMMdd 日期

Pandas 导出 to_csv() 在列名周围加上引号