0
0
Djangoframework~30 mins

File upload handling basics in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
File upload handling basics
📖 Scenario: You are building a simple Django web app where users can upload a profile picture. This project will guide you through setting up the data model, configuring the upload settings, writing the view to handle the file upload, and completing the template to show the upload form.
🎯 Goal: Build a Django app that allows users to upload a file and saves it to the server. The app will display a form to upload a profile picture and save the uploaded file in the model.
📋 What You'll Learn
Create a Django model with a FileField to store the uploaded file
Add a setting variable for the upload directory
Write a view function to handle the file upload and save it
Create a template with a form that allows file upload
💡 Why This Matters
🌍 Real World
File uploads are common in web apps for user profile pictures, documents, or media content. Handling uploads correctly is essential for user interaction.
💼 Career
Understanding file upload handling is a key skill for backend and full-stack developers working with Django or similar web frameworks.
Progress0 / 4 steps
1
Create the model with a FileField
Create a Django model called Profile in models.py with a profile_picture field using models.FileField and set upload_to='uploads/'.
Django
Need a hint?

Use models.FileField with the upload_to parameter to specify the folder.

2
Add upload directory setting
In settings.py, add a variable called MEDIA_ROOT and set it to BASE_DIR / 'media'. Also add MEDIA_URL = '/media/'.
Django
Need a hint?

Use BASE_DIR / 'media' to set the media root folder for uploads.

3
Write the view to handle file upload
In views.py, write a function called upload_profile_picture that handles a POST request. Use request.FILES['profile_picture'] to get the uploaded file, create a Profile instance with it, and save it.
Django
Need a hint?

Check if the request method is POST and the file is in request.FILES. Then create and save the model instance.

4
Create the upload form template
Create a template called upload.html with a form that uses method='POST' and enctype='multipart/form-data'. Add a file input with name='profile_picture' and a submit button.
Django
Need a hint?

Remember to add enctype='multipart/form-data' to the form tag for file uploads.