ashir nasir
ashir nasir

Reputation: 247

Django Executing Python Script

i am doing a copy cat with Need a minimal Django file upload example

i changed the view.py with my code to dump the csv file into sqlite database. i have already created the table in default sqlite database.

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)
    )

my code is starting from first introduction of gfile

Error @ line 20 : Coercing to unicode : need string or buffer, Document Found please help

Upvotes: 1

Views: 199

Answers (1)

alecxe
alecxe

Reputation: 473863

You are passing Document instance to open. Instead you should pass the file, that was uploaded directly to csv.reader:

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

Upvotes: 1

Related Questions