Testing File Uploads

A snippet showing how to test file uploads in Django.


# models.py

from django.db import models

class Upload(models.Model):
    file = models.FileField(upload_to="uploads/")
      

# admin.py

from django.contrib import admin
from .models import Upload

@admin.register(Upload)
class UploadAdmin(admin.ModelAdmin):
    list_display = ("file",)
      
 
# Result (tests/test_upload.py)
from django.test import TestCase
from django.core.files.uploadedfile import SimpleUploadedFile
from django.urls import reverse

class UploadTest(TestCase):
    def test_upload(self):
        f = SimpleUploadedFile("hello.txt", b"hello world", content_type="text/plain")
        res = self.client.post(reverse("upload"), {"file": f})
        self.assertEqual(res.status_code, 302)
      
Explanation:
  • Use SimpleUploadedFile to simulate file uploads in tests.
  • Check that an object is created and file saved to storage.
  • Category Testing
  • Total Views 946
  • Last Modified 08 April, 2026
  • Tags #testing #file upload #forms #client
Previous snippet
Testing JSON Responses
Next snippet
Testing Email Sending
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.