Bird
Raised Fist0
Djangoframework~20 mins

File upload handling basics in Django - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
File Upload Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when a file is uploaded using Django's default FileField?

Consider a Django model with a FileField. When a user uploads a file through a form linked to this model, what is the default behavior regarding the file storage?

Django
class Document(models.Model):
    upload = models.FileField(upload_to='uploads/')
AThe file is uploaded but not saved anywhere unless manually handled in the view.
BThe file is stored directly in the database as binary data.
CThe file is saved in a temporary folder and deleted after the request finishes.
DThe file is saved to the directory specified by <code>upload_to</code> inside the <code>MEDIA_ROOT</code> folder.
Attempts:
2 left
💡 Hint

Think about where Django stores uploaded files by default when using FileField.

📝 Syntax
intermediate
2:00remaining
Identify the correct way to handle file upload in a Django view

Which of the following Django view snippets correctly handles a file upload from a form?

Django
def upload_file(request):
    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES)
        if form.is_valid():
            # What should happen here?
            pass
    else:
        form = UploadForm()
    return render(request, 'upload.html', {'form': form})
Afile = request.FILES['file']; instance = Document(); instance.upload = file; instance.save()
Bfile = request.POST['file']; instance = Document(upload=file); instance.save()
Cfile = request.FILES.get('file'); instance = Document(); instance.upload = file; instance.save()
Dfile = request.FILES['file']; instance = Document(upload=file); instance.save()
Attempts:
2 left
💡 Hint

Remember that uploaded files are in request.FILES and you can assign them to model fields before saving.

🔧 Debug
advanced
2:00remaining
Why does this Django file upload view raise a MultiValueDictKeyError?

Examine the following Django view code snippet. It raises a MultiValueDictKeyError when no file is uploaded. Why?

Django
def upload_file(request):
    if request.method == 'POST':
        file = request.FILES['file']
        instance = Document(upload=file)
        instance.save()
    return render(request, 'upload.html')
ABecause <code>request.FILES['file']</code> assumes the file key always exists, but it may be missing if no file is uploaded.
BBecause the <code>Document</code> model does not have a <code>FileField</code> named <code>upload</code>.
CBecause the view does not check if the request method is GET before accessing <code>request.FILES</code>.
DBecause the file is too large and Django rejects it silently.
Attempts:
2 left
💡 Hint

Think about what happens if the form is submitted without a file.

❓ state_output
advanced
2:00remaining
What is the value of the model field after saving a file upload?

Given this Django model and view, what will be the value of instance.upload.name after saving a file named example.txt?

Django
class Document(models.Model):
    upload = models.FileField(upload_to='docs/')

def upload_file(request):
    if request.method == 'POST':
        file = request.FILES['file']
        instance = Document(upload=file)
        instance.save()
        return instance.upload.name
Aexample.txt
Bdocs/example.txt
CMEDIA_ROOT/docs/example.txt
D/docs/example.txt
Attempts:
2 left
💡 Hint

Remember that upload_to sets a folder path relative to MEDIA_ROOT.

🧠 Conceptual
expert
2:00remaining
Why is it important to use request.FILES instead of request.POST for file uploads in Django?

When handling file uploads in Django, why must you access uploaded files via request.FILES instead of request.POST?

A<code>request.FILES</code> is only used for images, while <code>request.POST</code> handles other file types.
B<code>request.POST</code> contains file data but in a compressed format that needs decoding.
C<code>request.FILES</code> contains file data as <code>UploadedFile</code> objects, while <code>request.POST</code> only contains text data from the form fields.
D<code>request.POST</code> is deprecated and should never be used.
Attempts:
2 left
💡 Hint

Think about how browsers send files in forms and how Django separates data.

Practice

(1/5)
1. What is the main purpose of request.FILES in Django when handling file uploads?
easy
A. To access the uploaded file data sent by the user
B. To store form validation errors
C. To save files directly to the database
D. To send files from the server to the client

Solution

  1. Step 1: Understand the role of request.FILES

    This attribute contains all files uploaded by the user in the current request.
  2. Step 2: Differentiate from other request attributes

    request.POST holds form data, but request.FILES specifically holds file data.
  3. Final Answer:

    To access the uploaded file data sent by the user -> Option A
  4. Quick Check:

    File data = request.FILES [OK]
Hint: Remember: files come in request.FILES, not request.POST [OK]
Common Mistakes:
  • Confusing request.FILES with request.POST
  • Thinking files are saved automatically
  • Assuming request.FILES is a file path
2. Which of the following is the correct way to define a file upload field in a Django form?
easy
A. file = forms.FileField()
B. file = forms.CharField()
C. file = models.FileField()
D. file = forms.ImageField()

Solution

  1. Step 1: Identify form field types for file uploads

    forms.FileField() is used in forms to accept any file upload.
  2. Step 2: Differentiate from model fields and other form fields

    models.FileField() is for models, not forms. forms.ImageField() is for images only.
  3. Final Answer:

    file = forms.FileField() -> Option A
  4. Quick Check:

    File upload field in form = FileField() [OK]
Hint: Use FileField() in forms, not CharField() or model fields [OK]
Common Mistakes:
  • Using CharField instead of FileField
  • Confusing model fields with form fields
  • Using ImageField for non-image files
3. Given this Django view snippet handling a file upload:
def upload_file(request):
    if request.method == 'POST':
        uploaded_file = request.FILES['file']
        with open('uploaded.txt', 'wb+') as destination:
            for chunk in uploaded_file.chunks():
                destination.write(chunk)
    return HttpResponse('Upload complete')

What will happen if the uploaded file is large?
medium
A. The file will cause a memory error because it is read all at once
B. The file will be saved in chunks to avoid memory issues
C. The file will be saved as text instead of binary
D. The file upload will fail because chunks() is not a valid method

Solution

  1. Step 1: Understand the use of chunks() method

    The chunks() method reads the uploaded file in small parts to avoid loading the entire file into memory.
  2. Step 2: Analyze the file saving logic

    The code writes each chunk to the file, so large files are handled safely without memory errors.
  3. Final Answer:

    The file will be saved in chunks to avoid memory issues -> Option B
  4. Quick Check:

    chunks() saves large files safely [OK]
Hint: chunks() method helps save large files safely [OK]
Common Mistakes:
  • Assuming chunks() reads whole file at once
  • Thinking chunks() is invalid method
  • Ignoring binary write mode 'wb+'
4. Identify the error in this Django view code for file upload:
def upload(request):
    if request.method == 'POST':
        file = request.POST['file']
        with open('file.txt', 'wb') as f:
            f.write(file.read())
    return HttpResponse('Done')
medium
A. Missing form validation before saving the file
B. Opening the file in write mode instead of append mode
C. Using request.POST instead of request.FILES to get the file
D. Not checking if the request method is GET

Solution

  1. Step 1: Check how the uploaded file is accessed

    The code uses request.POST['file'], but uploaded files are in request.FILES.
  2. Step 2: Understand the impact of this mistake

    Accessing the file from request.POST will cause a KeyError or wrong data type error.
  3. Final Answer:

    Using request.POST instead of request.FILES to get the file -> Option C
  4. Quick Check:

    Files come from request.FILES, not request.POST [OK]
Hint: Always get files from request.FILES, not request.POST [OK]
Common Mistakes:
  • Using request.POST for files
  • Not opening file in binary mode
  • Ignoring request method check
5. You want to save an uploaded file in Django but only if its size is less than 2MB. Which code snippet correctly checks the file size before saving?
hard
A. if uploaded_file.length < 2 * 1024 * 1024: with open('file.txt', 'w') as f: f.write(uploaded_file)
B. if len(uploaded_file) < 2 * 1024 * 1024: with open('file.txt', 'wb+') as f: f.write(uploaded_file.read())
C. if uploaded_file.size > 2 * 1024 * 1024: with open('file.txt', 'wb+') as f: for chunk in uploaded_file.chunks(): f.write(chunk)
D. if uploaded_file.size < 2 * 1024 * 1024: with open('file.txt', 'wb+') as f: for chunk in uploaded_file.chunks(): f.write(chunk)

Solution

  1. Step 1: Check the correct attribute for file size

    The size attribute gives the file size in bytes.
  2. Step 2: Verify the condition and saving method

    The condition checks if size is less than 2MB (2 * 1024 * 1024 bytes). The file is saved in chunks to handle large files safely.
  3. Final Answer:

    if uploaded_file.size < 2 * 1024 * 1024: with open('file.txt', 'wb+') as f: for chunk in uploaded_file.chunks(): f.write(chunk) -> Option D
  4. Quick Check:

    Use uploaded_file.size and chunks() to save safely [OK]
Hint: Use uploaded_file.size to check size before saving [OK]
Common Mistakes:
  • Using len() or length instead of size
  • Opening file in text mode 'w' instead of binary
  • Checking size with wrong comparison operator
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard