Complete the code to import the module needed to handle uploaded files in Django views.
from django.core.files import [1]
The django.core.files module provides classes and functions to handle uploaded files.
Complete the code to access the uploaded file from the request in a Django view.
uploaded_file = request.FILES.get('[1]')
The key used in request.FILES matches the name attribute of the file input in the HTML form. Commonly, it is 'file'.
Fix the error in saving the uploaded file to disk by completing the missing method call.
with open('uploads/' + uploaded_file.name, 'wb+') as destination: for chunk in uploaded_file.[1](): destination.write(chunk)
The chunks() method reads the uploaded file in small pieces to avoid memory issues.
Fill both blanks to create a Django form field that accepts file uploads and validates the file size.
from django import forms class UploadForm(forms.Form): file = forms.[1](required=True) def clean_file(self): file = self.cleaned_data.get('file') if file.size > [2]: raise forms.ValidationError('File too large') return file
FileField is used for file uploads in forms. The size limit is set in bytes; 1048576 bytes equals 1MB.
Fill all three blanks to write a Django view that saves an uploaded file using the default storage system.
from django.core.files.storage import [1] @csrf_exempt def upload_view(request): if request.method == 'POST' and request.FILES.get('file'): uploaded_file = request.FILES['file'] fs = [2]() filename = fs.[3](uploaded_file.name, uploaded_file) return HttpResponse(f'File saved as {filename}') return HttpResponse('Upload a file')
FileSystemStorage is the default storage class. The save() method saves the file and returns the filename.