5

Is it possible to upload a file in django with a FileField in a form but no model? So far I could only find examples with a model. I don't want to create a table for that in my database, I just want to upload a file. My form:

class csvUploadForm(forms.Form):
    csvFile = forms.FileField(label='Select a CSV file to upload.', help_text='help')

Thank you,

Romain

2
  • do you want to upload a file for parsing it? if so, this would work. else you would have to specify a storage location Commented Dec 4, 2012 at 13:44
  • Yes, I just need to parse it, not to store it. Is it possible? Commented Dec 4, 2012 at 14:32

2 Answers 2

7

Example reproduced from Django Documentation.

from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response

def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            handle_uploaded_file(request.FILES['file'])
            return HttpResponseRedirect('/success/url/')
    else:
        form = UploadFileForm()
    return render_to_response('upload.html', {'form': form})

def handle_uploaded_file(f):
    destination = open('some/file/name.txt', 'wb+')
    for chunk in f.chunks():
        destination.write(chunk)
    destination.close()

You can replace 'some/file/name.txt' with some other path where you want to store that file.

Sign up to request clarification or add additional context in comments.

3 Comments

But such solution lacks one important functionality provided by the model - storage. If one uses storage which stores files outside of local filesystem then this handler wouldn't do the job.
I'm with Jakub on this one. Obviously if you want to upload a file in Django, you want it to use Djangos media storage. Many people use S3 or other storage solutions and an answer to this question should take that into consideration. Downvote.
@Marcus Lind Jakub Jagiełło What you said is correct. Now please read comment number 2 on question by rom. He says "... I just need to parse it, not to store it. Is it possible?" What I suggested here is a way to catch uploaded file in form. I just reproduced example from the documentation. We can do many things with the file once we get it such as parse it in-memory store it on local disk or somewhere else. My point is rom didn't want to store :)
0

This is covered in the File Uploads section of the Django documentation. In short, use the UploadedFile instance given in request.FILES.

1 Comment

How to do? The documentation is not clear. The problem here is that my file is not uploaded to the server. I have checked MEDIA variables in settings.py and enctype in my template.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.