python - Processing an uploaded file using Django -
i'm attempting process uploaded csv file using django. main logic of how go doing expressed in both models.py
, views.py
scripts. once i've uploaded file, i'm unable process of content (in views.py
). here 2 scripts, if there's more information can provide, i'd happy to.
in models.py
file, have 2 classes, 1 document itself, , other class fields in file.
models.py:
from django.db import models import os class document(models.model): docfile = models.filefield(upload_to='documents') class documententry(models.model): document = models.foreignkey(document, on_delete=models.cascade) field = models.charfield(max_length=250, default="test")
next, in views.py
file uploaded via request.files['docfile']
, pass handle_files()
function. however, when try loop through reader, i'm unable access of elements in file uploaded.
views.py:
from django.shortcuts import render django.conf import settings django.http import httpresponseredirect django.core.urlresolvers import reverse import csv .models import document, documententry .forms import uploadfileform def process_file(request): # handle file upload if request.method == 'post': form = uploadfileform(request.post, request.files) if form.is_valid(): handle_files(request.files['docfile']) # redirect document list after post return httpresponseredirect(reverse('process_files')) else: form = uploadfileform() # empty, unbound form # load documents list page documents = document.objects.all() # render list page documents , form return render( request, 'upload/process_files.html', {'documents': documents, 'form': form} ) def handle_files(csv_file): newdoc = document(docfile=csv_file) newdoc.save() reader = csv.dictreader(open(csv_file)) row in reader: field = row['field'] entry = documententry(document=newdoc, field=field) entry.save()
updated
here full example of handler function:
def handle_files(csv_file): newdoc = document(docfile=csv_file) newdoc.save() open(newdoc.docfile.name) f: reader = csv.dictreader(f) row in reader: field = row['field'] entry = documententry(document=newdoc, field=field) entry.save()
Comments
Post a Comment