How Does Django Handle File Uploads

When I learn programming I was puzzled by the complex way of handling a file read-in/out. For example, in Python, according to w3schools tutorial, note that it’s highlighted that files need to be explicitly closed after opening, due to buffering, changes made to a file may not show until they are closed.
f = open(“demofile.txt”, “r”)
print(f.readline())
f.close()

f = open(“demofile2.txt”, “a”)
f.write(“Now the file has more content!”)
f.close()

“x” – Create – will create a file, returns an error if the file exist
“a” – Append – will create a file if the specified file does not exist
“w” – Write – will create a file if the specified file does not exist

When Django handles a file upload, the file data ends up placed in request.FILES. Take robo-indexing.herokuapp.com as an example, the views file contains two button design(html/templates) to take a seed csv file and a theme/string input.

if request.method == ‘POST’ and request.FILES[‘myfile’]:
myfile = request.FILES[‘myfile’]
theme = request.POST[‘theme’]
print(theme)

If there are multiple files to be uploaded, we set these in forms.py

from django import forms

class FileFieldForm(forms.Form):
    file_field = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))

Common way we take in upload files are

def handle_uploaded_file(f):
with open(‘some/file/name.txt’, ‘wb+’) as destination:
for chunk in f.chunks():
destination.write(chunk)

Then override the post method of your FormView subclass to handle multiple file uploads:

from django.views.generic.edit import FormView
from .forms import FileFieldForm

class FileFieldView(FormView):
    form_class = FileFieldForm
    template_name = 'upload.html'  # Replace with your template.
    success_url = '...'  # Replace with your URL or reverse().

    def post(self, request, *args, **kwargs):
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        files = request.FILES.getlist('file_field')
        if form.is_valid():
            for f in files:
                ...  # Do something with each file.
            return self.form_valid(form)
        else:
            return self.form_invalid(form)

in comparison the single file uploading views.py as

Note when files are uploaded, Django passes off to handles to handle:

["django.core.files.uploadhandler.MemoryFileUploadHandler",
 "django.core.files.uploadhandler.TemporaryFileUploadHandler"]

It makes it easy in Django web framework work, using such on the fly commands as “request.upload_handlers.insert(0, ProgressBarUploadHandler(request))” for AJAX widget in-woven there.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.