rom
rom

Reputation: 3672

django upload file no model

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

Upvotes: 5

Views: 6624

Answers (2)

Aryaveer
Aryaveer

Reputation: 943

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.

Upvotes: 7

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798576

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

Upvotes: 0

Related Questions