1. ============
    
  2. File Uploads
    
  3. ============
    
  4. 
    
  5. .. currentmodule:: django.core.files.uploadedfile
    
  6. 
    
  7. When Django handles a file upload, the file data ends up placed in
    
  8. :attr:`request.FILES <django.http.HttpRequest.FILES>` (for more on the
    
  9. ``request`` object see the documentation for :doc:`request and response objects
    
  10. </ref/request-response>`). This document explains how files are stored on disk
    
  11. and in memory, and how to customize the default behavior.
    
  12. 
    
  13. .. warning::
    
  14. 
    
  15.     There are security risks if you are accepting uploaded content from
    
  16.     untrusted users! See the security guide's topic on
    
  17.     :ref:`user-uploaded-content-security` for mitigation details.
    
  18. 
    
  19. Basic file uploads
    
  20. ==================
    
  21. 
    
  22. Consider a form containing a :class:`~django.forms.FileField`:
    
  23. 
    
  24. .. code-block:: python
    
  25.     :caption: ``forms.py``
    
  26. 
    
  27.     from django import forms
    
  28. 
    
  29.     class UploadFileForm(forms.Form):
    
  30.         title = forms.CharField(max_length=50)
    
  31.         file = forms.FileField()
    
  32. 
    
  33. A view handling this form will receive the file data in
    
  34. :attr:`request.FILES <django.http.HttpRequest.FILES>`, which is a dictionary
    
  35. containing a key for each :class:`~django.forms.FileField` (or
    
  36. :class:`~django.forms.ImageField`, or other :class:`~django.forms.FileField`
    
  37. subclass) in the form. So the data from the above form would
    
  38. be accessible as ``request.FILES['file']``.
    
  39. 
    
  40. Note that :attr:`request.FILES <django.http.HttpRequest.FILES>` will only
    
  41. contain data if the request method was ``POST``, at least one file field was
    
  42. actually posted, and the ``<form>`` that posted the request has the attribute
    
  43. ``enctype="multipart/form-data"``. Otherwise, ``request.FILES`` will be empty.
    
  44. 
    
  45. Most of the time, you'll pass the file data from ``request`` into the form as
    
  46. described in :ref:`binding-uploaded-files`. This would look something like:
    
  47. 
    
  48. .. code-block:: python
    
  49.     :caption: ``views.py``
    
  50. 
    
  51.     from django.http import HttpResponseRedirect
    
  52.     from django.shortcuts import render
    
  53.     from .forms import UploadFileForm
    
  54. 
    
  55.     # Imaginary function to handle an uploaded file.
    
  56.     from somewhere import handle_uploaded_file
    
  57. 
    
  58.     def upload_file(request):
    
  59.         if request.method == 'POST':
    
  60.             form = UploadFileForm(request.POST, request.FILES)
    
  61.             if form.is_valid():
    
  62.                 handle_uploaded_file(request.FILES['file'])
    
  63.                 return HttpResponseRedirect('/success/url/')
    
  64.         else:
    
  65.             form = UploadFileForm()
    
  66.         return render(request, 'upload.html', {'form': form})
    
  67. 
    
  68. Notice that we have to pass :attr:`request.FILES <django.http.HttpRequest.FILES>`
    
  69. into the form's constructor; this is how file data gets bound into a form.
    
  70. 
    
  71. Here's a common way you might handle an uploaded file::
    
  72. 
    
  73.     def handle_uploaded_file(f):
    
  74.         with open('some/file/name.txt', 'wb+') as destination:
    
  75.             for chunk in f.chunks():
    
  76.                 destination.write(chunk)
    
  77. 
    
  78. Looping over ``UploadedFile.chunks()`` instead of using ``read()`` ensures that
    
  79. large files don't overwhelm your system's memory.
    
  80. 
    
  81. There are a few other methods and attributes available on ``UploadedFile``
    
  82. objects; see :class:`UploadedFile` for a complete reference.
    
  83. 
    
  84. Handling uploaded files with a model
    
  85. ------------------------------------
    
  86. 
    
  87. If you're saving a file on a :class:`~django.db.models.Model` with a
    
  88. :class:`~django.db.models.FileField`, using a :class:`~django.forms.ModelForm`
    
  89. makes this process much easier. The file object will be saved to the location
    
  90. specified by the :attr:`~django.db.models.FileField.upload_to` argument of the
    
  91. corresponding :class:`~django.db.models.FileField` when calling
    
  92. ``form.save()``::
    
  93. 
    
  94.     from django.http import HttpResponseRedirect
    
  95.     from django.shortcuts import render
    
  96.     from .forms import ModelFormWithFileField
    
  97. 
    
  98.     def upload_file(request):
    
  99.         if request.method == 'POST':
    
  100.             form = ModelFormWithFileField(request.POST, request.FILES)
    
  101.             if form.is_valid():
    
  102.                 # file is saved
    
  103.                 form.save()
    
  104.                 return HttpResponseRedirect('/success/url/')
    
  105.         else:
    
  106.             form = ModelFormWithFileField()
    
  107.         return render(request, 'upload.html', {'form': form})
    
  108. 
    
  109. If you are constructing an object manually, you can assign the file object from
    
  110. :attr:`request.FILES <django.http.HttpRequest.FILES>` to the file field in the
    
  111. model::
    
  112. 
    
  113.     from django.http import HttpResponseRedirect
    
  114.     from django.shortcuts import render
    
  115.     from .forms import UploadFileForm
    
  116.     from .models import ModelWithFileField
    
  117. 
    
  118.     def upload_file(request):
    
  119.         if request.method == 'POST':
    
  120.             form = UploadFileForm(request.POST, request.FILES)
    
  121.             if form.is_valid():
    
  122.                 instance = ModelWithFileField(file_field=request.FILES['file'])
    
  123.                 instance.save()
    
  124.                 return HttpResponseRedirect('/success/url/')
    
  125.         else:
    
  126.             form = UploadFileForm()
    
  127.         return render(request, 'upload.html', {'form': form})
    
  128. 
    
  129. If you are constructing an object manually outside of a request, you can assign
    
  130. a :class:`~django.core.files.File` like object to the
    
  131. :class:`~django.db.models.FileField`::
    
  132. 
    
  133.     from django.core.management.base import BaseCommand
    
  134.     from django.core.files.base import ContentFile
    
  135. 
    
  136.     class MyCommand(BaseCommand):
    
  137.         def handle(self, *args, **options):
    
  138.             content_file = ContentFile(b'Hello world!', name='hello-world.txt')
    
  139.             instance = ModelWithFileField(file_field=content_file)
    
  140.             instance.save()
    
  141. 
    
  142. .. _uploading_multiple_files:
    
  143. 
    
  144. Uploading multiple files
    
  145. ------------------------
    
  146. 
    
  147. ..
    
  148.     Tests in tests.forms_tests.field_tests.test_filefield.MultipleFileFieldTest
    
  149.     should be updated after any changes in the following snippets.
    
  150. 
    
  151. If you want to upload multiple files using one form field, create a subclass
    
  152. of the field's widget and set the ``allow_multiple_selected`` attribute on it
    
  153. to ``True``.
    
  154. 
    
  155. In order for such files to be all validated by your form (and have the value of
    
  156. the field include them all), you will also have to subclass ``FileField``. See
    
  157. below for an example.
    
  158. 
    
  159. .. admonition:: Multiple file field
    
  160. 
    
  161.     Django is likely to have a proper multiple file field support at some point
    
  162.     in the future.
    
  163. 
    
  164. .. code-block:: python
    
  165.     :caption: ``forms.py``
    
  166. 
    
  167.     from django import forms
    
  168. 
    
  169.     class MultipleFileInput(forms.ClearableFileInput):
    
  170.         allow_multiple_selected = True
    
  171. 
    
  172. 
    
  173.     class MultipleFileField(forms.FileField):
    
  174.         def __init__(self, *args, **kwargs):
    
  175.             kwargs.setdefault("widget", MultipleFileInput())
    
  176.             super().__init__(*args, **kwargs)
    
  177. 
    
  178.         def clean(self, data, initial=None):
    
  179.             single_file_clean = super().clean
    
  180.             if isinstance(data, (list, tuple)):
    
  181.                 result = [single_file_clean(d, initial) for d in data]
    
  182.             else:
    
  183.                 result = single_file_clean(data, initial)
    
  184.             return result
    
  185. 
    
  186. 
    
  187.     class FileFieldForm(forms.Form):
    
  188.         file_field = MultipleFileField()
    
  189. 
    
  190. Then override the ``post`` method of your
    
  191. :class:`~django.views.generic.edit.FormView` subclass to handle multiple file
    
  192. uploads:
    
  193. 
    
  194. .. code-block:: python
    
  195.     :caption: ``views.py``
    
  196. 
    
  197.     from django.views.generic.edit import FormView
    
  198.     from .forms import FileFieldForm
    
  199. 
    
  200.     class FileFieldFormView(FormView):
    
  201.         form_class = FileFieldForm
    
  202.         template_name = 'upload.html'  # Replace with your template.
    
  203.         success_url = '...'  # Replace with your URL or reverse().
    
  204. 
    
  205.         def post(self, request, *args, **kwargs):
    
  206.             form_class = self.get_form_class()
    
  207.             form = self.get_form(form_class)
    
  208.             if form.is_valid():
    
  209.                 return self.form_valid(form)
    
  210.             else:
    
  211.                 return self.form_invalid(form)
    
  212. 
    
  213.         def form_valid(self, form):
    
  214.             files = form.cleaned_data["file_field"]
    
  215.             for f in files:
    
  216.                 ...  # Do something with each file.
    
  217.             return super().form_valid()
    
  218. 
    
  219. .. warning::
    
  220. 
    
  221.    This will allow you to handle multiple files at the form level only. Be
    
  222.    aware that you cannot use it to put multiple files on a single model
    
  223.    instance (in a single field), for example, even if the custom widget is used
    
  224.    with a form field related to a model ``FileField``.
    
  225. 
    
  226. .. versionchanged:: 3.2.19
    
  227. 
    
  228.    In previous versions, there was no support for the ``allow_multiple_selected``
    
  229.    class attribute, and users were advised to create the widget with the HTML
    
  230.    attribute ``multiple`` set through the ``attrs`` argument. However, this
    
  231.    caused validation of the form field to be applied only to the last file
    
  232.    submitted, which could have adverse security implications.
    
  233. 
    
  234. Upload Handlers
    
  235. ===============
    
  236. 
    
  237. .. currentmodule:: django.core.files.uploadhandler
    
  238. 
    
  239. When a user uploads a file, Django passes off the file data to an *upload
    
  240. handler* -- a small class that handles file data as it gets uploaded. Upload
    
  241. handlers are initially defined in the :setting:`FILE_UPLOAD_HANDLERS` setting,
    
  242. which defaults to::
    
  243. 
    
  244.     ["django.core.files.uploadhandler.MemoryFileUploadHandler",
    
  245.      "django.core.files.uploadhandler.TemporaryFileUploadHandler"]
    
  246. 
    
  247. Together :class:`MemoryFileUploadHandler` and
    
  248. :class:`TemporaryFileUploadHandler` provide Django's default file upload
    
  249. behavior of reading small files into memory and large ones onto disk.
    
  250. 
    
  251. You can write custom handlers that customize how Django handles files. You
    
  252. could, for example, use custom handlers to enforce user-level quotas, compress
    
  253. data on the fly, render progress bars, and even send data to another storage
    
  254. location directly without storing it locally. See :ref:`custom_upload_handlers`
    
  255. for details on how you can customize or completely replace upload behavior.
    
  256. 
    
  257. Where uploaded data is stored
    
  258. -----------------------------
    
  259. 
    
  260. Before you save uploaded files, the data needs to be stored somewhere.
    
  261. 
    
  262. By default, if an uploaded file is smaller than 2.5 megabytes, Django will hold
    
  263. the entire contents of the upload in memory. This means that saving the file
    
  264. involves only a read from memory and a write to disk and thus is very fast.
    
  265. 
    
  266. However, if an uploaded file is too large, Django will write the uploaded file
    
  267. to a temporary file stored in your system's temporary directory. On a Unix-like
    
  268. platform this means you can expect Django to generate a file called something
    
  269. like ``/tmp/tmpzfp6I6.upload``. If an upload is large enough, you can watch this
    
  270. file grow in size as Django streams the data onto disk.
    
  271. 
    
  272. These specifics -- 2.5 megabytes; ``/tmp``; etc. -- are "reasonable defaults"
    
  273. which can be customized as described in the next section.
    
  274. 
    
  275. Changing upload handler behavior
    
  276. --------------------------------
    
  277. 
    
  278. There are a few settings which control Django's file upload behavior. See
    
  279. :ref:`File Upload Settings <file-upload-settings>` for details.
    
  280. 
    
  281. .. _modifying_upload_handlers_on_the_fly:
    
  282. 
    
  283. Modifying upload handlers on the fly
    
  284. ------------------------------------
    
  285. 
    
  286. Sometimes particular views require different upload behavior. In these cases,
    
  287. you can override upload handlers on a per-request basis by modifying
    
  288. ``request.upload_handlers``. By default, this list will contain the upload
    
  289. handlers given by :setting:`FILE_UPLOAD_HANDLERS`, but you can modify the list
    
  290. as you would any other list.
    
  291. 
    
  292. For instance, suppose you've written a ``ProgressBarUploadHandler`` that
    
  293. provides feedback on upload progress to some sort of AJAX widget. You'd add this
    
  294. handler to your upload handlers like this::
    
  295. 
    
  296.     request.upload_handlers.insert(0, ProgressBarUploadHandler(request))
    
  297. 
    
  298. You'd probably want to use ``list.insert()`` in this case (instead of
    
  299. ``append()``) because a progress bar handler would need to run *before* any
    
  300. other handlers. Remember, the upload handlers are processed in order.
    
  301. 
    
  302. If you want to replace the upload handlers completely, you can assign a new
    
  303. list::
    
  304. 
    
  305.    request.upload_handlers = [ProgressBarUploadHandler(request)]
    
  306. 
    
  307. .. note::
    
  308. 
    
  309.     You can only modify upload handlers *before* accessing
    
  310.     ``request.POST`` or ``request.FILES`` -- it doesn't make sense to
    
  311.     change upload handlers after upload handling has already
    
  312.     started. If you try to modify ``request.upload_handlers`` after
    
  313.     reading from ``request.POST`` or ``request.FILES`` Django will
    
  314.     throw an error.
    
  315. 
    
  316.     Thus, you should always modify uploading handlers as early in your view as
    
  317.     possible.
    
  318. 
    
  319.     Also, ``request.POST`` is accessed by
    
  320.     :class:`~django.middleware.csrf.CsrfViewMiddleware` which is enabled by
    
  321.     default. This means you will need to use
    
  322.     :func:`~django.views.decorators.csrf.csrf_exempt` on your view to allow you
    
  323.     to change the upload handlers.  You will then need to use
    
  324.     :func:`~django.views.decorators.csrf.csrf_protect` on the function that
    
  325.     actually processes the request.  Note that this means that the handlers may
    
  326.     start receiving the file upload before the CSRF checks have been done.
    
  327.     Example code::
    
  328. 
    
  329.         from django.views.decorators.csrf import csrf_exempt, csrf_protect
    
  330. 
    
  331.         @csrf_exempt
    
  332.         def upload_file_view(request):
    
  333.             request.upload_handlers.insert(0, ProgressBarUploadHandler(request))
    
  334.             return _upload_file_view(request)
    
  335. 
    
  336.         @csrf_protect
    
  337.         def _upload_file_view(request):
    
  338.             ... # Process request
    
  339. 
    
  340.     If you are using a class-based view, you will need to use
    
  341.     :func:`~django.views.decorators.csrf.csrf_exempt` on its
    
  342.     :meth:`~django.views.generic.base.View.dispatch` method and
    
  343.     :func:`~django.views.decorators.csrf.csrf_protect` on the method that
    
  344.     actually processes the request. Example code::
    
  345. 
    
  346.         from django.utils.decorators import method_decorator
    
  347.         from django.views import View
    
  348.         from django.views.decorators.csrf import csrf_exempt, csrf_protect
    
  349. 
    
  350.         @method_decorator(csrf_exempt, name='dispatch')
    
  351.         class UploadFileView(View):
    
  352. 
    
  353.             def setup(self, request, *args, **kwargs):
    
  354.                 request.upload_handlers.insert(0, ProgressBarUploadHandler(request))
    
  355.                 super().setup(request, *args, **kwargs)
    
  356. 
    
  357.             @method_decorator(csrf_protect)
    
  358.             def post(self, request, *args, **kwargs):
    
  359.                 ... # Process request