Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Processing an uploaded file using Django

I'm attempting to process an uploaded CSV file using Django. The main logic of how I go about doing this is expressed in both the models.py and views.py scripts. Once I've uploaded the file, I'm unable to process any of the content (in my views.py). Here are the two scripts, but if there's any more information I can provide, I'd be happy to.

In my models.py file, I have two classes, one for the document itself, and the other class for the fields in the 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 my views.py I get the file that was uploaded via the request.FILES['docfile'] and pass it to the handle_files() function. However, when I try to loop through the reader, I'm unable to access any of the elements in the file that was uploaded.

views.py:

from django.shortcuts import render
from django.conf import settings
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse

import csv

from .models import Document, DocumentEntry
from .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 to the document list after POST
            return HttpResponseRedirect(reverse('process_files'))
    else:
        form = UploadFileForm()  # 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(
        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))
    for row in reader:
        field = row['field']
        entry = DocumentEntry(document=newdoc, field=field)
        entry.save()
like image 346
Vincent Russo Avatar asked Nov 17 '16 19:11

Vincent Russo


1 Answers

Updated

Here is full example of handler function:

def handle_files(csv_file):

   newdoc = Document(docfile=csv_file)
   newdoc.save()

   with open(newdoc.docfile.name) as f:
      reader = csv.DictReader(f)
      for row in reader:
         field = row['field']
         entry = DocumentEntry(document=newdoc, field=field)
         entry.save()
like image 178
Gagik Sukiasyan Avatar answered Sep 29 '22 05:09

Gagik Sukiasyan