Django provides a straightforward way to handle file uploads through its forms and models framework. File uploads in Django are managed using the FileField or ImageField fields, along with configurations in settings for file storage.
Steps for File Upload in Django
1. Configure Settings
Add the MEDIA_URL and MEDIA_ROOT settings in your settings.py file to specify where uploaded files will be stored:
# settings.py
MEDIA_URL = '/media/' # URL to access media files in development
MEDIA_ROOT = BASE_DIR / 'media' # Directory to store uploaded files
2. Create a File Upload Form
Create a form with a FileField or ImageField to handle file inputs.
# forms.py
from django import forms
class FileUploadForm(forms.Form):
file = forms.FileField(label="Select a file")
3. Create a Model for File Upload
If you want to save uploaded files in the database, define a model with a FileField or ImageField.
# models.py
from django.db import models
class UploadedFile(models.Model):
name = models.CharField(max_length=255)
file = models.FileField(upload_to='uploads/') # Files will be saved in MEDIA_ROOT/uploads/
uploaded_at = models.DateTimeField(auto_now_add=True)
4. Create a View to Handle File Upload
The view processes the uploaded file and saves it to the specified location.
# views.py
from django.shortcuts import render
from .forms import FileUploadForm
def file_upload_view(request):
if request.method == 'POST':
form = FileUploadForm(request.POST, request.FILES)
if form.is_valid():
uploaded_file = form.cleaned_data['file']
# Save the file or process it as needed
with open(f'media/uploads/{uploaded_file.name}', 'wb+') as destination:
for chunk in uploaded_file.chunks():
destination.write(chunk)
return render(request, 'upload_success.html', {'file_name': uploaded_file.name})
else:
form = FileUploadForm()
return render(request, 'file_upload.html', {'form': form})
Save files into the Database (Using the model)
# views.py
from django.shortcuts import render
from .models import UploadedFile
from .forms import FileUploadForm
def file_upload_view(request):
if request.method == 'POST':
form = FileUploadForm(request.POST, request.FILES)
if form.is_valid():
uploaded_file = UploadedFile(
name=request.FILES['file'].name,
file=request.FILES['file']
)
uploaded_file.save()
return render(request, 'upload_success.html', {'file_name': uploaded_file.file.url})
else:
form = FileUploadForm()
return render(request, 'file_upload.html', {'form': form})
5. Create a Template for File Upload
Create an HTML form to allow users to upload files.
#file_upload.html
{% load static %}
<!DOCTYPE html>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<h1>Upload a File</h1>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload</button>
</form>
</body>
</html>
6. Configure URL Patterns
Add the URL patterns to serve uploaded files during development.
# urls.py
from django.conf import settings
from django.conf.urls.static import static
from django.urls import path
from . import views
urlpatterns = [
path('upload/', views.file_upload_view, name='file_upload'),
]
if settings.DEBUG: # Serve media files in development
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)