Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Managing Uploaded Files in Django

Introduction

Uploading files is a common feature in web applications. Django provides a powerful set of tools and utilities to handle file uploads. This tutorial will guide you through the process of managing uploaded files in a Django application, from setup to handling and saving files.

Setting Up the Project

First, ensure you have Django installed. If not, you can install it using pip:

pip install django

Create a new Django project and app:

django-admin startproject fileupload

cd fileupload

python manage.py startapp uploads

Configuring Settings

Open settings.py and add the following configurations:

Add 'uploads' to INSTALLED_APPS:

INSTALLED_APPS = [
    ...
    'uploads',
]
                

Configure media settings:

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
                

Creating Models

Define a model to handle file uploads in uploads/models.py:

from django.db import models

class Document(models.Model):
    description = models.CharField(max_length=255, blank=True)
    document = models.FileField(upload_to='documents/')
    uploaded_at = models.DateTimeField(auto_now_add=True)
                

Run migrations to create the necessary database tables:

python manage.py makemigrations

python manage.py migrate

Creating Forms

Create a form for uploading files in uploads/forms.py:

from django import forms
from .models import Document

class DocumentForm(forms.ModelForm):
    class Meta:
        model = Document
        fields = ('description', 'document',)
                

Creating Views

Handle file uploads in uploads/views.py:

from django.shortcuts import render, redirect
from django.http import HttpResponse
from .forms import DocumentForm
from .models import Document

def upload_file(request):
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect('file_list')
    else:
        form = DocumentForm()
    return render(request, 'upload.html', {'form': form})

def file_list(request):
    documents = Document.objects.all()
    return render(request, 'file_list.html', {'documents': documents})
                

Creating Templates

Create templates for uploading and listing files:

upload.html:

<!DOCTYPE html>
<html>
<head>
    <title>Upload File</title>
</head>
<body>
    <h1>Upload File</h1>
    <form method="post" enctype="multipart/form-data">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Upload</button>
    </form>
</body>
</html>
                

file_list.html:

<!DOCTYPE html>
<html>
<head>
    <title>File List</title>
</head>
<body>
    <h1>File List</h1>
    <ul>
        {% for document in documents %}
            <li>
                <a href="{{ document.document.url }}">{{ document.description }}</a>
            </li>
        {% endfor %}
    </ul>
</body>
</html>
                

Configuring URLs

Configure URLs for the views in uploads/urls.py:

from django.urls import path
from .views import upload_file, file_list

urlpatterns = [
    path('upload/', upload_file, name='upload_file'),
    path('', file_list, name='file_list'),
]
                

Include the app URLs in the project’s urls.py:

from django.conf import settings
from django.conf.urls.static import static
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('uploads.urls')),
]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
                

Testing the Application

Run the server and test the application:

python manage.py runserver

Visit http://127.0.0.1:8000/upload/ to upload files and http://127.0.0.1:8000/ to view the list of uploaded files.

Conclusion

In this tutorial, we covered the process of managing file uploads in a Django application. We configured settings, created models, forms, views, and templates, and tested the application. This should give you a solid foundation for handling file uploads in your Django projects.