File Uploads

    Warning

    There are security risks if you are accepting uploaded content from untrusted users! See the security guide’s topic on User-uploaded content for mitigation details.

    Consider a form containing a :

    forms.py

    A view handling this form will receive the file data in request.FILES, which is a dictionary containing a key for each (or ImageField, or other subclass) in the form. So the data from the above form would be accessible as request.FILES['file'].

    Note that request.FILES will only 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.

    Most of the time, you’ll pass the file data from request into the form as described in . This would look something like:

    views.py

    1. from django.http import HttpResponseRedirect
    2. from django.shortcuts import render
    3. from .forms import UploadFileForm
    4. # Imaginary function to handle an uploaded file.
    5. from somewhere import handle_uploaded_file
    6. def upload_file(request):
    7. if request.method == 'POST':
    8. form = UploadFileForm(request.POST, request.FILES)
    9. if form.is_valid():
    10. handle_uploaded_file(request.FILES['file'])
    11. return HttpResponseRedirect('/success/url/')
    12. else:
    13. form = UploadFileForm()
    14. return render(request, 'upload.html', {'form': form})

    Notice that we have to pass request.FILES into the form’s constructor; this is how file data gets bound into a form.

    Here’s a common way you might handle an uploaded file:

    1. def handle_uploaded_file(f):
    2. with open('some/file/name.txt', 'wb+') as destination:
    3. for chunk in f.chunks():
    4. destination.write(chunk)

    Looping over UploadedFile.chunks() instead of using read() ensures that large files don’t overwhelm your system’s memory.

    If you’re saving a file on a with a FileField, using a makes this process much easier. The file object will be saved to the location specified by the upload_to argument of the corresponding when calling form.save():

    1. from django.http import HttpResponseRedirect
    2. from django.shortcuts import render
    3. def upload_file(request):
    4. form = ModelFormWithFileField(request.POST, request.FILES)
    5. if form.is_valid():
    6. # file is saved
    7. form.save()
    8. return HttpResponseRedirect('/success/url/')
    9. else:
    10. form = ModelFormWithFileField()
    11. return render(request, 'upload.html', {'form': form})

    If you are constructing an object manually, you can assign the file object from request.FILES to the file field in the model:

    If you want to upload multiple files using one form field, set the multiple HTML attribute of field’s widget:

    forms.py

    1. from django import forms
    2. class FileFieldForm(forms.Form):
    3. file_field = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))

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

    views.py

    1. from django.views.generic.edit import FormView
    2. from .forms import FileFieldForm
    3. class FileFieldFormView(FormView):
    4. form_class = FileFieldForm
    5. template_name = 'upload.html' # Replace with your template.
    6. success_url = '...' # Replace with your URL or reverse().
    7. def post(self, request, *args, **kwargs):
    8. form_class = self.get_form_class()
    9. form = self.get_form(form_class)
    10. files = request.FILES.getlist('file_field')
    11. if form.is_valid():
    12. for f in files:
    13. return self.form_valid(form)
    14. else:
    15. return self.form_invalid(form)

    Upload Handlers

    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, which defaults to:

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

    Together MemoryFileUploadHandler and provide Django’s default file upload behavior of reading small files into memory and large ones onto disk.

    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 Writing custom upload handlers for details on how you can customize or completely replace upload behavior.

    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.

    These specifics – 2.5 megabytes; ; etc. – are “reasonable defaults” which can be customized as described in the next section.

    There are a few settings which control Django’s file upload behavior. See for details.

    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 handlers given by FILE_UPLOAD_HANDLERS, but you can modify the list as you would any other list.

    For instance, suppose you’ve written a ProgressBarUploadHandler that provides feedback on upload progress to some sort of AJAX widget. You’d add this handler to your upload handlers like this:

    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.

    If you want to replace the upload handlers completely, you can assign a new list:

    1. request.upload_handlers = [ProgressBarUploadHandler(request)]

    Note

    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.

    Thus, you should always modify uploading handlers as early in your view as possible.

    Also, request.POST is accessed by which is enabled by default. This means you will need to use csrf_exempt() on your view to allow you to change the upload handlers. You will then need to use 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. Example code:

    1. from django.views.decorators.csrf import csrf_exempt, csrf_protect
    2. @csrf_exempt
    3. def upload_file_view(request):
    4. request.upload_handlers.insert(0, ProgressBarUploadHandler(request))
    5. return _upload_file_view(request)
    6. @csrf_protect
    7. def _upload_file_view(request):
    8. ... # Process request

    If you are using a class-based view, you will need to use csrf_exempt() on its method and csrf_protect() on the method that actually processes the request. Example code:

    1. from django.utils.decorators import method_decorator
    2. from django.views import View
    3. from django.views.decorators.csrf import csrf_exempt, csrf_protect
    4. @method_decorator(csrf_exempt, name='dispatch')
    5. class UploadFileView(View):
    6. def setup(self, request, *args, **kwargs):
    7. request.upload_handlers.insert(0, ProgressBarUploadHandler(request))
    8. super().setup(request, *args, **kwargs)
    9. @method_decorator(csrf_protect)
    10. def post(self, request, *args, **kwargs):