Enabling users to upload multiple files and effortlessly displaying them on a single page is a crucial feature for various web applications. Whether you’re creating a collaborative platform, a media sharing website, or any application involving file interaction, facilitating multiple file uploads and seamless display enhances both user experience and functionality. In this comprehensive tutorial, we’ll guide you through implementing this capability in a Django web application, incorporating the changes you’ve provided.
Prerequisites
Before we begin, ensure you have the following prerequisites in place:
- Django: Make sure you have Django installed. You can install it using
pip
if needed:
pip install Django
- Basic Understanding of Django: Familiarity with creating views, templates, forms, and models in Django will be beneficial.
Note: This project can be used with any database as it is. No changes needed. You can learn how to Configure Database with our bellow blogs:
Step 1: Setting Up Your Django Project
Start by creating a new Django project and app if you haven’t already. Open your terminal and run the following commands:
django-admin startproject myproject
cd myproject
python manage.py startapp fileuploads
Step 2: Defining Your Model
Begin by defining a simple model to store information about uploaded files. Open fileuploads/models.py
and define the model:
from django.db import models
class UploadedFile(models.Model):
file = models.FileField(upload_to='uploads/')
uploaded_at = models.DateTimeField(auto_now_add=True)
Here, we’ve created the UploadedFile
model with a FileField
to store the uplooded file and a timestamp to record the upload time.
Step 3: Creating Views
Now, let’s create views to manage file uploads and display uploaded files on the same page. Open fileuploads/views.py
and define the views:
from django.shortcuts import render, redirect
from .models import UploadedFile
from .forms import UploadFileForm
def upload_and_display_files(request):
files = UploadedFile.objects.all()
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
for uploaded_file in request.FILES.getlist('files'):
UploadedFile.objects.create(file=uploaded_file)
return redirect('upload_and_display')
else:
form = UploadFileForm()
return render(request, 'upload_and_display.html', {'form': form, 'files': files})
In the upload_and_display_files
view, we handle both the file upload form submission and the display of uploaded files.
Step 4: Creating Forms
Let’s create a form that supports multiple file uploads using the provided classes. Define the UploadFileForm
form in the fileuploads/forms.py
file:
from django import forms
class MultipleFileInput(forms.ClearableFileInput):
allow_multiple_selected = True
class MultipleFileField(forms.FileField):
def __init__(self, *args, **kwargs):
kwargs.setdefault("widget", MultipleFileInput())
super().__init__(*args, **kwargs)
def clean(self, data, initial=None):
single_file_clean = super().clean
if isinstance(data, (list, tuple)):
result = [single_file_clean(d, initial) for d in data]
else:
result = single_file_clean(data, initial)
return result
class UploadFileForm(forms.Form):
files = MultipleFileField()
In this UploadFileForm
, we’ve incorporated the MultipleFileField
that supports multiple file uploads using the MultipleFileInput
widget.
Step 5: Configuring URLs
Configure the URLs to correspond to the views you’ve created. Open the fileuploads/urls.py
file and define the URL:
from django.urls import path
from . import views
urlpatterns = [
path('', views.upload_and_display_files, name='upload_and_display'),
]
This URL pattern enables users to access the page where they can upload files and view uploaded files simultaneously.
Step 6: Creating Templates
Generate the HTML template for the page where users can upload files and view uploaded files together. Inside the fileuploads/templates
folder, create an HTML file named upload_and_display.html
.
<!-- fileuploads/templates/upload_and_display.html -->
<!DOCTYPE html>
<html>
<head>
<title>Upload and Display Files</title>
</head>
<body>
<h2>Upload and Display Files</h2>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload</button>
</form>
<h3>Uploaded Files:</h3>
<ul>
{% for file in files %}
<li><a href="{{ file.file.url }}">{{ file.file.name }}</a></li>
{% empty %}
<li>No files uploaded yet.</li>
{% endfor %}
</ul>
</body>
</html>
This template harmoniously combines the file upload form and the display of uploaded files on one page.
Step 7: Configuring Media Settings and App URLs
In your project’s settings (myproject/settings.py
), configure the media settings to manage file uploads. Add the following lines at the end of the file:
import os
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Lastly, include the URLs of the fileuploads
app in the project’s main urls.py
file (
):myproject
/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('fileuploads.urls')),
]
from django.conf import settings
from django.conf.urls.static import static
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Step 8: Running Migrations and Starting the Server
Run the initial migrations to create the necessary database tables:
python manage.py makemigrations
python manage.py migrate
Now, start the development server:
python manage.py runserver
Visit http://127.0.0.1:8000/
in your browser to access the page where you can both upload and view files simultaneously.
Conclusion
Congratulations! You’ve successfully implemented the capability to upload multiple files and seamlessly display them on the same page in your Django application. By following this comprehensive guide, you’ve established the foundational components, including models, views, forms, templates, and configurations, to create an interactive and user-friendly file management feature. This functionality empowers you to build applications that involve collaborative content creation, media sharing, and document management, enhancing user engagement and interactivity.
Find this project on Github.
Blogs You Might Like to Read!
- How To Upload and Download Files in Django
- How to Upload and Display Image in Django using ImageField
- Create Image Gallery with Multiple Image Upload in Django
- Folder and File Structure for Django Templates: Best Practices
- Django Bootstrap – Integrate Template Example
- Best Folder and Directory Structure for a Django Project
- How to Restrict and Protect Access to Media Files in Django with Example
- How to Crop Image Before Upload in Django Website