0

Thanks for helping.

I have a view that allows me to upload a csv file and to read it. I want this file's data to be put in one of my template (and hence on a webpage). My view looks like this:

@login_required
def uploadFunc(request, username):
 user = get_object_or_404(User, username=username)
 if request.method == 'GET':
    return render_to_response('upload.html',{'user':user},context_instance=RequestContext(request))
 elif request.method == 'POST':
    with open('penguins.csv', 'rb') as f:
        reader = csv.reader(f)
        for m in reader:
            print m
        return HttpResponseRedirect("/")

As you can see from

print m
return HttpResponseRedirect("/")

I print the data extracted (it gets printed to terminal, but not a webpage), and then redirect the upload page to my home page where a table out of the penguin.csv (don't laugh at the name! I know:)) should be constructed. Thing is I do not understand (or know) how do I let my template index.html to know that it is that file that should be put in that table.

Sorry for a lot of talk, if it is confusing feel free to ask questions.

Thanks again, blargie-bla

blargie-bla
  • 37
  • 2
  • 11
  • There are a few things I don't understand: where's the file upload? You are opening a file, but I don't see you saving one. Also, the last return line, why is it there? are you expecting to call this method with other methods but get and post? – Nitzan Tomer Feb 29 '12 at 19:32
  • Thanks for asking! the file that is going to be opened is in django folder and I don't know why I don't save it:( I am quite new to the uploading in general. The return line, errr, I think I need to delete it:) – blargie-bla Feb 29 '12 at 19:35

1 Answers1

1

You need to first upload the file and save it into disk (or memory), then you need to save the this state for the next request. You have a few methods of doing that, for example in the session.

Here's an example, it's not tested and might have some errors...

FILE_UPLOAD_DIR = '/tmp'

class UploadFileForm(forms.Form):
    file = forms.FileField()

@login_required
def uploadFunc(request, username):
    user = get_object_or_404(User, username=username)
    if request.method == 'GET':
        return render_to_response('upload.html',{'user':user},context_instance=RequestContext(request))
    elif request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            path = _handle_uploaded_file(request.FILES['file'])
            request.session['uploaded_file'] = path
            return HttpResponseRedirect("/")

def index(request):
    if request.session.get("uploaded_file", None):
        lines = []
        with open(request.session.pop("uploaded_file"), 'rb') as f:
            reader = csv.reader(f)
            for m in reader:
                lines.append(m)

        return render_to_response('index.html', { 'file_lines': lines }, context_instance=RequestContext(request))


def _handle_uploaded_file(source):
    fd, filepath = tempfile.mkstemp(prefix=source.name, dir=FILE_UPLOAD_DIR)
    with open(filepath, 'wb') as dest:
        shutil.copyfileobj(source, dest)
    return filepath

Then in the template for index.html you can use the file_lines to populate the table.

I "glued" this code from various snippets I found just now, here's the list of urls:

Community
  • 1
  • 1
Nitzan Tomer
  • 155,636
  • 47
  • 315
  • 299