Upload a File in Django

As a developer, I’ve worked on many web applications that require handling file uploads. Whether you’re building a job application portal where users upload resumes or a media sharing platform where images and videos are submitted, file uploading is a fundamental feature.

Django makes handling file uploads simple once you understand the core concepts. In this article, I’ll walk you through practical, easy-to-follow methods for uploading files in Django. By the end, you’ll be able to implement file uploads confidently in your projects.

Understand File Uploads in Django

Django handles file uploads through its forms system and model fields designed for files. The uploaded files are temporarily stored in memory or on disk before you save them permanently.

The key components involved are:

  • FileField or ImageField in models to store file references.
  • HTML forms with enctype="multipart/form-data" to enable file uploads.
  • Handling uploaded files in views.
  • Configuring media settings to serve uploaded files.

Let me show you how to set this up step by step.

Read How to Encrypt and Decrypt Passwords in Django

Method 1: Upload Files Using a Model Form

This is the most common and recommended way to handle file uploads in Django, especially when you want to associate uploaded files with database records.

Step 1: Set up Your Django Project

Make sure your Django project is created and running. For this example, I assume you have a project named myproject and an app named fileupload.

Step 2: Configure Media Settings

In your settings.py, add the following to handle media files:

import os

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

This tells Django where to store uploaded files and how to serve them during development.

Also, update your project’s main urls.py to serve media files:

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

urlpatterns = [
    path('', include('fileupload.urls')),
]

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

Step 3: Create Your Model

In fileupload/models.py, define a model with a FileField:

from django.db import models

class Document(models.Model):
    title = models.CharField(max_length=255)
    uploaded_file = models.FileField(upload_to='documents/')

    def __str__(self):
        return self.title

Here, files will be uploaded to media/documents/.

Step 4: Create a ModelForm

In fileupload/forms.py:

from django import forms
from .models import Document

class DocumentForm(forms.ModelForm):
    class Meta:
        model = Document
        fields = ['title', 'uploaded_file']

Step 5: Create Views to Handle Uploads

In fileupload/views.py:

from django.shortcuts import render, redirect
from .forms import DocumentForm

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, 'fileupload/upload.html', {'form': form})

def file_list(request):
    from .models import Document
    files = Document.objects.all()
    return render(request, 'fileupload/file_list.html', {'files': files})

Step 6: Set up URLs

In fileupload/urls.py:

from django.urls import path
from . import views

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

Check out Python Django Form Validation

Step 7: Create Templates

Create fileupload/templates/fileupload/upload.html:

<!DOCTYPE html>
<html>
<head>
    <title>Upload File</title>
</head>
<body>
    <h2>Upload a Document</h2>
    <form method="post" enctype="multipart/form-data">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Upload</button>
    </form>
    <a href="{% url 'file_list' %}">View Uploaded Files</a>
</body>
</html>

Create fileupload/templates/fileupload/file_list.html:

<!DOCTYPE html>
<html>
<head>
    <title>Uploaded Files</title>
</head>
<body>
    <h2>Uploaded Documents</h2>
    <ul>
        {% for file in files %}
            <li>{{ file.title }} - <a href="{{ file.uploaded_file.url }}" target="_blank">Download</a></li>
        {% empty %}
            <li>No files uploaded yet.</li>
        {% endfor %}
    </ul>
    <a href="{% url 'upload_file' %}">Upload a New File</a>
</body>
</html>

Step 8: Run Migrations and Test

python manage.py makemigrations
python manage.py migrate
python manage.py runserver

Visit http://127.0.0.1:8000/upload/ to upload your files.

You can refer to the screenshot below to see the output:

django file upload

http://127.0.0.1:8000/files/ to see the uploaded files.

django upload file
file upload Django

Read Login system in Python Django

Method 2: Upload Files Without a Model (Manual Handling)

Sometimes, you may want to upload files without saving them in a model. For example, uploading a profile picture temporarily or processing files on the fly.

Here’s how you can do it:

Step 1: Create a Form

In fileupload/forms.py:

from django import forms

class UploadFileForm(forms.Form):
    file = forms.FileField()

Step 2: Create a View to Handle Upload

In fileupload/views.py:

from django.shortcuts import render
from .forms import UploadFileForm

def handle_uploaded_file(f):
    with open('media/temp/' + f.name, 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)

def upload_file_manual(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            handle_uploaded_file(request.FILES['file'])
            return render(request, 'fileupload/upload_success.html', {'filename': request.FILES['file'].name})
    else:
        form = UploadFileForm()
    return render(request, 'fileupload/upload_manual.html', {'form': form})

Step 3: Create URLs

In fileupload/urls.py:

from django.urls import path
from . import views

urlpatterns = [
    path('upload/manual/', views.upload_file_manual, name='upload_file_manual'),
]

Check out Python Django Random Number

Step 4: Create Templates

fileupload/templates/fileupload/upload_manual.html:

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

fileupload/templates/fileupload/upload_success.html:

<!DOCTYPE html>
<html>
<head>
    <title>Upload Success</title>
</head>
<body>
    <h2>File "{{ filename }}" uploaded successfully!</h2>
    <a href="{% url 'upload_file_manual' %}">Upload another file</a>
</body>
</html>

Step 5: Create the Temporary Folder

Make sure the folder media/temp/ exists and is writable by your Django app.

Read Python Django Format Date

Tips From My Experience

  • Always validate uploaded files, especially if you allow users to upload images or documents. Check file types and sizes to avoid security risks.
  • Use Django’s ImageField if you specifically want to upload images, as it integrates with the Pillow library for image validation.
  • For production, configure your web server (e.g., Nginx or Apache) to serve media files efficiently.
  • Consider asynchronous file processing if uploads involve large files or heavy processing.
  • Remember to secure your media URLs if the files are sensitive or private.

Uploading files in Django is simple once you understand the workflow. Whether you want to use model forms or handle files manually, Django provides the tools to make the process smooth. Start implementing file uploads in your projects today, and you’ll see how this feature can enhance your web apps.

If you want to dive deeper, check out the detailed tutorials on file uploads and viewing uploaded files in Django on PythonGuides.com for more examples and best practices.

You may also read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.