2008-07-01 15:10:51 +00:00
|
|
|
============
|
|
|
|
File Uploads
|
|
|
|
============
|
|
|
|
|
2011-02-16 01:56:53 +00:00
|
|
|
.. currentmodule:: django.core.files.uploadedfile
|
2008-08-23 22:25:40 +00:00
|
|
|
|
2008-11-18 06:35:05 +00:00
|
|
|
When Django handles a file upload, the file data ends up placed in
|
2010-02-24 13:57:46 +00:00
|
|
|
:attr:`request.FILES <django.http.HttpRequest.FILES>` (for more on the
|
2010-08-19 19:27:44 +00:00
|
|
|
``request`` object see the documentation for :doc:`request and response objects
|
|
|
|
</ref/request-response>`). This document explains how files are stored on disk
|
2010-02-24 13:57:46 +00:00
|
|
|
and in memory, and how to customize the default behavior.
|
2008-07-01 15:10:51 +00:00
|
|
|
|
2013-11-13 12:38:03 +00:00
|
|
|
.. warning::
|
|
|
|
|
|
|
|
There are security risks if you are accepting uploaded content from
|
|
|
|
untrusted users! See the security guide's topic on
|
|
|
|
:ref:`user-uploaded-content-security` for mitigation details.
|
|
|
|
|
2008-07-01 15:10:51 +00:00
|
|
|
Basic file uploads
|
|
|
|
==================
|
|
|
|
|
2019-06-17 14:54:55 +00:00
|
|
|
Consider a form containing a :class:`~django.forms.FileField`:
|
2016-06-04 13:24:30 +00:00
|
|
|
|
2018-09-10 17:00:34 +00:00
|
|
|
.. code-block:: python
|
|
|
|
:caption: forms.py
|
2008-07-01 15:10:51 +00:00
|
|
|
|
2008-07-21 16:38:54 +00:00
|
|
|
from django import forms
|
2008-07-01 15:10:51 +00:00
|
|
|
|
|
|
|
class UploadFileForm(forms.Form):
|
|
|
|
title = forms.CharField(max_length=50)
|
2014-08-04 11:29:59 +00:00
|
|
|
file = forms.FileField()
|
2008-07-07 23:16:00 +00:00
|
|
|
|
2010-02-24 13:57:46 +00:00
|
|
|
A view handling this form will receive the file data in
|
|
|
|
:attr:`request.FILES <django.http.HttpRequest.FILES>`, which is a dictionary
|
|
|
|
containing a key for each :class:`~django.forms.FileField` (or
|
|
|
|
:class:`~django.forms.ImageField`, or other :class:`~django.forms.FileField`
|
|
|
|
subclass) in the form. So the data from the above form would
|
2008-07-01 15:10:51 +00:00
|
|
|
be accessible as ``request.FILES['file']``.
|
|
|
|
|
2010-02-24 13:57:46 +00:00
|
|
|
Note that :attr:`request.FILES <django.http.HttpRequest.FILES>` will only
|
2020-09-16 08:22:38 +00:00
|
|
|
contain data if the request method was ``POST``, at least one file field was
|
|
|
|
actually posted, and the ``<form>`` that posted the request has the attribute
|
|
|
|
``enctype="multipart/form-data"``. Otherwise, ``request.FILES`` will be empty.
|
2009-05-17 18:45:25 +00:00
|
|
|
|
2019-06-17 14:54:55 +00:00
|
|
|
Most of the time, you'll pass the file data from ``request`` into the form as
|
|
|
|
described in :ref:`binding-uploaded-files`. This would look something like:
|
2016-06-04 13:24:30 +00:00
|
|
|
|
2018-09-10 17:00:34 +00:00
|
|
|
.. code-block:: python
|
|
|
|
:caption: views.py
|
2008-07-01 15:10:51 +00:00
|
|
|
|
|
|
|
from django.http import HttpResponseRedirect
|
2015-12-22 15:21:24 +00:00
|
|
|
from django.shortcuts import render
|
2013-05-18 12:00:52 +00:00
|
|
|
from .forms import UploadFileForm
|
2008-07-01 15:10:51 +00:00
|
|
|
|
|
|
|
# Imaginary function to handle an uploaded file.
|
|
|
|
from somewhere import handle_uploaded_file
|
|
|
|
|
|
|
|
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()
|
2015-12-22 15:21:24 +00:00
|
|
|
return render(request, 'upload.html', {'form': form})
|
2008-07-01 15:10:51 +00:00
|
|
|
|
2010-02-24 13:57:46 +00:00
|
|
|
Notice that we have to pass :attr:`request.FILES <django.http.HttpRequest.FILES>`
|
|
|
|
into the form's constructor; this is how file data gets bound into a form.
|
2008-07-01 15:10:51 +00:00
|
|
|
|
2014-03-26 13:30:47 +00:00
|
|
|
Here's a common way you might handle an uploaded file::
|
2008-07-01 15:10:51 +00:00
|
|
|
|
2014-03-26 13:30:47 +00:00
|
|
|
def handle_uploaded_file(f):
|
|
|
|
with open('some/file/name.txt', 'wb+') as destination:
|
|
|
|
for chunk in f.chunks():
|
|
|
|
destination.write(chunk)
|
2011-02-16 01:56:53 +00:00
|
|
|
|
2014-03-26 13:30:47 +00:00
|
|
|
Looping over ``UploadedFile.chunks()`` instead of using ``read()`` ensures that
|
|
|
|
large files don't overwhelm your system's memory.
|
2011-02-16 01:56:53 +00:00
|
|
|
|
2014-03-26 13:30:47 +00:00
|
|
|
There are a few other methods and attributes available on ``UploadedFile``
|
|
|
|
objects; see :class:`UploadedFile` for a complete reference.
|
2008-07-01 15:10:51 +00:00
|
|
|
|
2014-03-26 13:30:47 +00:00
|
|
|
Handling uploaded files with a model
|
|
|
|
------------------------------------
|
2008-07-07 23:16:00 +00:00
|
|
|
|
2014-03-26 13:30:47 +00:00
|
|
|
If you're saving a file on a :class:`~django.db.models.Model` with a
|
|
|
|
:class:`~django.db.models.FileField`, using a :class:`~django.forms.ModelForm`
|
|
|
|
makes this process much easier. The file object will be saved to the location
|
|
|
|
specified by the :attr:`~django.db.models.FileField.upload_to` argument of the
|
|
|
|
corresponding :class:`~django.db.models.FileField` when calling
|
|
|
|
``form.save()``::
|
2011-02-16 01:56:53 +00:00
|
|
|
|
2014-03-26 13:30:47 +00:00
|
|
|
from django.http import HttpResponseRedirect
|
|
|
|
from django.shortcuts import render
|
|
|
|
from .forms import ModelFormWithFileField
|
2008-07-07 23:16:00 +00:00
|
|
|
|
2014-03-26 13:30:47 +00:00
|
|
|
def upload_file(request):
|
|
|
|
if request.method == 'POST':
|
|
|
|
form = ModelFormWithFileField(request.POST, request.FILES)
|
|
|
|
if form.is_valid():
|
|
|
|
# file is saved
|
|
|
|
form.save()
|
|
|
|
return HttpResponseRedirect('/success/url/')
|
|
|
|
else:
|
|
|
|
form = ModelFormWithFileField()
|
|
|
|
return render(request, 'upload.html', {'form': form})
|
2011-02-16 01:56:53 +00:00
|
|
|
|
2019-06-17 14:54:55 +00:00
|
|
|
If you are constructing an object manually, you can assign the file object from
|
|
|
|
:attr:`request.FILES <django.http.HttpRequest.FILES>` to the file field in the
|
|
|
|
model::
|
2008-07-07 23:16:00 +00:00
|
|
|
|
2014-03-26 13:30:47 +00:00
|
|
|
from django.http import HttpResponseRedirect
|
|
|
|
from django.shortcuts import render
|
|
|
|
from .forms import UploadFileForm
|
|
|
|
from .models import ModelWithFileField
|
2008-07-07 23:16:00 +00:00
|
|
|
|
2014-03-26 13:30:47 +00:00
|
|
|
def upload_file(request):
|
|
|
|
if request.method == 'POST':
|
|
|
|
form = UploadFileForm(request.POST, request.FILES)
|
|
|
|
if form.is_valid():
|
|
|
|
instance = ModelWithFileField(file_field=request.FILES['file'])
|
|
|
|
instance.save()
|
|
|
|
return HttpResponseRedirect('/success/url/')
|
|
|
|
else:
|
|
|
|
form = UploadFileForm()
|
|
|
|
return render(request, 'upload.html', {'form': form})
|
2011-02-16 01:56:53 +00:00
|
|
|
|
2022-01-26 14:05:33 +00:00
|
|
|
If you are constructing an object manually outside of a request, you can assign
|
|
|
|
a :class:`~django.core.files.File` like object to the
|
|
|
|
:class:`~django.db.models.FileField`::
|
|
|
|
|
|
|
|
from django.core.management.base import BaseCommand
|
|
|
|
from django.core.files.base import ContentFile
|
|
|
|
|
|
|
|
class MyCommand(BaseCommand):
|
|
|
|
def handle(self, *args, **options):
|
|
|
|
content_file = ContentFile(b'Hello world!', name='hello-world.txt')
|
|
|
|
instance = ModelWithFileField(file_field=content_file)
|
|
|
|
instance.save()
|
|
|
|
|
2016-05-15 07:03:31 +00:00
|
|
|
Uploading multiple files
|
|
|
|
------------------------
|
|
|
|
|
|
|
|
If you want to upload multiple files using one form field, set the ``multiple``
|
|
|
|
HTML attribute of field's widget:
|
|
|
|
|
2018-09-10 17:00:34 +00:00
|
|
|
.. code-block:: python
|
|
|
|
:caption: forms.py
|
2016-05-15 07:03:31 +00:00
|
|
|
|
|
|
|
from django import forms
|
|
|
|
|
|
|
|
class FileFieldForm(forms.Form):
|
|
|
|
file_field = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))
|
|
|
|
|
|
|
|
Then override the ``post`` method of your
|
|
|
|
:class:`~django.views.generic.edit.FormView` subclass to handle multiple file
|
|
|
|
uploads:
|
|
|
|
|
2018-09-10 17:00:34 +00:00
|
|
|
.. code-block:: python
|
|
|
|
:caption: views.py
|
2016-05-15 07:03:31 +00:00
|
|
|
|
|
|
|
from django.views.generic.edit import FormView
|
|
|
|
from .forms import FileFieldForm
|
|
|
|
|
2021-03-01 21:54:22 +00:00
|
|
|
class FileFieldFormView(FormView):
|
2016-05-15 07:03:31 +00:00
|
|
|
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)
|
|
|
|
|
2014-03-26 13:30:47 +00:00
|
|
|
Upload Handlers
|
|
|
|
===============
|
2008-07-07 23:16:00 +00:00
|
|
|
|
2014-03-26 13:30:47 +00:00
|
|
|
.. currentmodule:: django.core.files.uploadhandler
|
2011-02-16 01:56:53 +00:00
|
|
|
|
2014-03-26 13:30:47 +00:00
|
|
|
When a user uploads a file, Django passes off the file data to an *upload
|
|
|
|
handler* -- a small class that handles file data as it gets uploaded. Upload
|
|
|
|
handlers are initially defined in the :setting:`FILE_UPLOAD_HANDLERS` setting,
|
|
|
|
which defaults to::
|
2008-07-07 23:16:00 +00:00
|
|
|
|
2015-01-21 16:55:57 +00:00
|
|
|
["django.core.files.uploadhandler.MemoryFileUploadHandler",
|
|
|
|
"django.core.files.uploadhandler.TemporaryFileUploadHandler"]
|
2008-07-01 15:10:51 +00:00
|
|
|
|
2014-03-26 13:30:47 +00:00
|
|
|
Together :class:`MemoryFileUploadHandler` and
|
|
|
|
:class:`TemporaryFileUploadHandler` provide Django's default file upload
|
|
|
|
behavior of reading small files into memory and large ones onto disk.
|
2008-07-07 23:16:00 +00:00
|
|
|
|
2014-03-26 13:30:47 +00:00
|
|
|
You can write custom handlers that customize how Django handles files. You
|
|
|
|
could, for example, use custom handlers to enforce user-level quotas, compress
|
|
|
|
data on the fly, render progress bars, and even send data to another storage
|
|
|
|
location directly without storing it locally. See :ref:`custom_upload_handlers`
|
|
|
|
for details on how you can customize or completely replace upload behavior.
|
2008-07-01 15:10:51 +00:00
|
|
|
|
|
|
|
Where uploaded data is stored
|
|
|
|
-----------------------------
|
|
|
|
|
|
|
|
Before you save uploaded files, the data needs to be stored somewhere.
|
|
|
|
|
|
|
|
By default, if an uploaded file is smaller than 2.5 megabytes, Django will hold
|
|
|
|
the entire contents of the upload in memory. This means that saving the file
|
|
|
|
involves only a read from memory and a write to disk and thus is very fast.
|
|
|
|
|
|
|
|
However, if an uploaded file is too large, Django will write the uploaded file
|
|
|
|
to a temporary file stored in your system's temporary directory. On a Unix-like
|
|
|
|
platform this means you can expect Django to generate a file called something
|
|
|
|
like ``/tmp/tmpzfp6I6.upload``. If an upload is large enough, you can watch this
|
|
|
|
file grow in size as Django streams the data onto disk.
|
|
|
|
|
2019-06-17 14:54:55 +00:00
|
|
|
These specifics -- 2.5 megabytes; ``/tmp``; etc. -- are "reasonable defaults"
|
|
|
|
which can be customized as described in the next section.
|
2008-07-01 15:10:51 +00:00
|
|
|
|
|
|
|
Changing upload handler behavior
|
|
|
|
--------------------------------
|
|
|
|
|
2014-08-23 13:30:01 +00:00
|
|
|
There are a few settings which control Django's file upload behavior. See
|
|
|
|
:ref:`File Upload Settings <file-upload-settings>` for details.
|
2011-09-09 17:20:16 +00:00
|
|
|
|
2018-06-27 17:55:09 +00:00
|
|
|
.. _modifying_upload_handlers_on_the_fly:
|
|
|
|
|
2008-07-01 15:10:51 +00:00
|
|
|
Modifying upload handlers on the fly
|
|
|
|
------------------------------------
|
|
|
|
|
|
|
|
Sometimes particular views require different upload behavior. In these cases,
|
|
|
|
you can override upload handlers on a per-request basis by modifying
|
|
|
|
``request.upload_handlers``. By default, this list will contain the upload
|
2011-05-29 17:41:04 +00:00
|
|
|
handlers given by :setting:`FILE_UPLOAD_HANDLERS`, but you can modify the list
|
|
|
|
as you would any other list.
|
2008-07-01 15:10:51 +00:00
|
|
|
|
|
|
|
For instance, suppose you've written a ``ProgressBarUploadHandler`` that
|
|
|
|
provides feedback on upload progress to some sort of AJAX widget. You'd add this
|
2008-08-23 22:25:40 +00:00
|
|
|
handler to your upload handlers like this::
|
2008-07-01 15:10:51 +00:00
|
|
|
|
2016-06-04 23:58:23 +00:00
|
|
|
request.upload_handlers.insert(0, ProgressBarUploadHandler(request))
|
2008-07-01 15:10:51 +00:00
|
|
|
|
|
|
|
You'd probably want to use ``list.insert()`` in this case (instead of
|
|
|
|
``append()``) because a progress bar handler would need to run *before* any
|
|
|
|
other handlers. Remember, the upload handlers are processed in order.
|
|
|
|
|
2019-06-17 14:54:55 +00:00
|
|
|
If you want to replace the upload handlers completely, you can assign a new
|
2008-07-01 15:10:51 +00:00
|
|
|
list::
|
|
|
|
|
2016-06-04 23:58:23 +00:00
|
|
|
request.upload_handlers = [ProgressBarUploadHandler(request)]
|
2008-07-01 15:10:51 +00:00
|
|
|
|
|
|
|
.. note::
|
|
|
|
|
2008-08-31 10:23:36 +00:00
|
|
|
You can only modify upload handlers *before* accessing
|
|
|
|
``request.POST`` or ``request.FILES`` -- it doesn't make sense to
|
|
|
|
change upload handlers after upload handling has already
|
|
|
|
started. If you try to modify ``request.upload_handlers`` after
|
|
|
|
reading from ``request.POST`` or ``request.FILES`` Django will
|
|
|
|
throw an error.
|
2008-07-01 15:10:51 +00:00
|
|
|
|
|
|
|
Thus, you should always modify uploading handlers as early in your view as
|
|
|
|
possible.
|
|
|
|
|
2010-09-29 16:35:34 +00:00
|
|
|
Also, ``request.POST`` is accessed by
|
|
|
|
:class:`~django.middleware.csrf.CsrfViewMiddleware` which is enabled by
|
2011-08-06 20:34:04 +00:00
|
|
|
default. This means you will need to use
|
2010-09-29 16:35:34 +00:00
|
|
|
:func:`~django.views.decorators.csrf.csrf_exempt` on your view to allow you
|
2011-08-06 20:34:04 +00:00
|
|
|
to change the upload handlers. You will then need to use
|
|
|
|
:func:`~django.views.decorators.csrf.csrf_protect` on the function that
|
|
|
|
actually processes the request. Note that this means that the handlers may
|
|
|
|
start receiving the file upload before the CSRF checks have been done.
|
2014-08-18 14:30:44 +00:00
|
|
|
Example code::
|
2010-09-29 16:35:34 +00:00
|
|
|
|
|
|
|
from django.views.decorators.csrf import csrf_exempt, csrf_protect
|
|
|
|
|
|
|
|
@csrf_exempt
|
|
|
|
def upload_file_view(request):
|
2016-06-04 23:58:23 +00:00
|
|
|
request.upload_handlers.insert(0, ProgressBarUploadHandler(request))
|
2010-09-29 16:35:34 +00:00
|
|
|
return _upload_file_view(request)
|
|
|
|
|
|
|
|
@csrf_protect
|
|
|
|
def _upload_file_view(request):
|
|
|
|
... # Process request
|
2021-10-12 08:09:29 +00:00
|
|
|
|
|
|
|
If you are using a class-based view, you will need to use
|
|
|
|
:func:`~django.views.decorators.csrf.csrf_exempt` on its
|
|
|
|
:meth:`~django.views.generic.base.View.dispatch` method and
|
|
|
|
:func:`~django.views.decorators.csrf.csrf_protect` on the method that
|
|
|
|
actually processes the request. Example code::
|
|
|
|
|
|
|
|
from django.utils.decorators import method_decorator
|
|
|
|
from django.views import View
|
|
|
|
from django.views.decorators.csrf import csrf_exempt, csrf_protect
|
|
|
|
|
|
|
|
@method_decorator(csrf_exempt, name='dispatch')
|
|
|
|
class UploadFileView(View):
|
|
|
|
|
|
|
|
def setup(self, request, *args, **kwargs):
|
|
|
|
request.upload_handlers.insert(0, ProgressBarUploadHandler(request))
|
|
|
|
super().setup(request, *args, **kwargs)
|
|
|
|
|
|
|
|
@method_decorator(csrf_protect)
|
|
|
|
def post(self, request, *args, **kwargs):
|
|
|
|
... # Process request
|