0
0
Djangoframework~10 mins

File upload handling basics in Django - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the module needed to handle uploaded files in Django views.

Django
from django.core.files import [1]
Drag options to blanks, or click blank then click option'
Afiles
Buploadhandler
Cstorage
Dupload
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'uploadhandler' which is a different module.
Using 'storage' which is for file storage backends.
2fill in blank
medium

Complete the code to access the uploaded file from the request in a Django view.

Django
uploaded_file = request.FILES.get('[1]')
Drag options to blanks, or click blank then click option'
Aupload
Bimage
Cdocument
Dfile
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'upload' which is not the default input name.
Using 'image' or 'document' without matching the form input.
3fill in blank
hard

Fix the error in saving the uploaded file to disk by completing the missing method call.

Django
with open('uploads/' + uploaded_file.name, 'wb+') as destination:
    for chunk in uploaded_file.[1]():
        destination.write(chunk)
Drag options to blanks, or click blank then click option'
Achunks
Bread
Creadlines
Dgetchunks
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'read' which reads the whole file at once.
Using 'readlines' which is for text files line by line.
4fill in blank
hard

Fill both blanks to create a Django form field that accepts file uploads and validates the file size.

Django
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
Drag options to blanks, or click blank then click option'
AFileField
BCharField
C1000000
D1048576
Attempts:
3 left
💡 Hint
Common Mistakes
Using CharField which is for text input.
Setting size limit as 1000000 which is close but not exact 1MB.
5fill in blank
hard

Fill all three blanks to write a Django view that saves an uploaded file using the default storage system.

Django
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')
Drag options to blanks, or click blank then click option'
AFileSystemStorage
Csave
Dstore
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'store' which is not a method of FileSystemStorage.
Using a different storage class not imported.