Media Files & Uploads
By the end of this lesson BookShelf staff will be able to upload a cover image for any book from the React book page. Django will check that each file is a real JPEG, PNG or WebP image of a sensible size, store it under a random name, and return its URL in the book JSON. You will also know how uploaded files are served on your laptop and why that changes in production.
What you should know first: Login, Protected Routes & Sessions (only staff will see the upload form), ViewSets, Routers & Permissions and the Django course's Static & Media Files. Versions checked: Pillow 13.0.0, Django 6.1.3, Django REST Framework 3.18.3.
Static files and media files
Django separates two kinds of files, and mixing them up causes real trouble later.
| Static files | Media files | |
|---|---|---|
| What | CSS, JavaScript, icons that you wrote | Files that users upload: covers, photos, PDFs |
| When they change | When you deploy | Any time, while the site runs |
| In Git? | Yes | Never (backend/media/ is already in .gitignore) |
| Settings | STATIC_URL, STATIC_ROOT | MEDIA_URL, MEDIA_ROOT |
| Trust | Trusted, you made them | Untrusted, a stranger made them |
In BookShelf the React build is the main "static" part, and the web server serves it from dist. This lesson is about the other column. Think of a school notice board in Kochi: the printed timetable is static, pinned by the office. Notices that students pin up are media. Someone must check each one before it goes up, and nobody expects them to stay forever.
Step 1: install Pillow
Django's ImageField uses Pillow, the Python imaging library, to open each upload and confirm it is a real image. Without it, Django refuses to start. We checked by hiding Pillow and running python manage.py check after Step 3's model change:
SystemCheckError: System check identified some issues: ERRORS: books.Book.cover: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow".
Install it in the venv and pin it:
python -m pip install pillow
python -m pip freeze > requirements.txtSuccessfully installed pillow-13.0.0
Step 2: MEDIA settings
Add these below STATIC_URL in config/settings.py:
# User uploads (book covers). Never inside the code folder in production.
MEDIA_URL = "media/"
MEDIA_ROOT = Path(os.environ.get("DJANGO_MEDIA_ROOT", BASE_DIR / "media"))MEDIA_ROOT is the folder on disk where files are saved. MEDIA_URL is the URL prefix they are served under, so media/covers/x.jpg on disk becomes /media/covers/x.jpg in the browser. The folder comes from an environment variable because on a server it should live outside the code folder, for example /srv/bookshelf/media, so a fresh deployment never deletes uploads. Add DJANGO_MEDIA_ROOT= with a comment to .env.example.
Step 3: a cover field with a safe file name
In books/models.py, add two imports at the top (from pathlib import Path and from uuid import uuid4), a function above Book, and one field:
def cover_upload_to(book, filename):
"""Store covers as covers/<random>.<ext>, never under the uploader's file name."""
return f"covers/{uuid4().hex}{Path(filename).suffix.lower()}"
class Book(models.Model):
# ... title, author, published_year, summary as before ...
cover = models.ImageField(upload_to=cover_upload_to, blank=True)
created_at = models.DateTimeField(auto_now_add=True)Why a random name? The uploader chooses the original file name. It might be priya-aadhaar-scan.jpg, which leaks personal details in a public URL, or a strange name full of dots and spaces. A random 32-character name reveals nothing and cannot be guessed. blank=True means a book may have no cover. Migrate:
python manage.py makemigrations books
python manage.py migrate booksMigrations for 'books':
books\migrations\0002_book_cover.py
+ Add field cover to book
Operations to perform:
Apply all migrations: books
Running migrations:
Applying books.0002_book_cover... OKStep 4: serializers that check the file
In BookSerializer, add "cover" to fields after "summary", and make it read-only, so ordinary book edits with JSON never touch it:
read_only_fields = ["cover", "created_at"] # covers go through /cover/Uploads get their own small serializer in books/serializers.py:
MAX_COVER_BYTES = 2 * 1024 * 1024 # 2 MB
MAX_COVER_SIDE = 3000 # pixels
COVER_FORMATS = {"JPEG", "PNG", "WEBP"}
class BookCoverSerializer(serializers.ModelSerializer):
cover = serializers.ImageField() # required here; Pillow checks it is a real image
class Meta:
model = Book
fields = ["cover"]
def validate_cover(self, file):
if file.size > MAX_COVER_BYTES:
raise serializers.ValidationError("The cover must be 2 MB or smaller.")
image = file.image # the Pillow image that ImageField opened
if image.format not in COVER_FORMATS:
raise serializers.ValidationError("Use a JPEG, PNG or WebP image.")
if max(image.size) > MAX_COVER_SIDE:
raise serializers.ValidationError("The cover must be at most 3000 pixels wide and high.")
return fileThere are three layers here. ImageField asks Pillow to open the file; a text file renamed to .jpg fails at this point. Then we check the real format that Pillow found inside the file, not the name or the Content-Type the browser sent, because both are chosen by the uploader. Finally we limit bytes and pixels, so nobody fills your disk or sends a huge image that is slow to show.
Step 5: an upload action, staff only
Add an action to BookViewSet in books/views.py (import MultiPartParser from rest_framework.parsers and BookCoverSerializer):
@action(detail=True, methods=["post", "delete"], parser_classes=[MultiPartParser])
def cover(self, request, pk=None):
"""POST a file as 'cover' to set or replace it; DELETE to remove it. Staff only."""
book = self.get_object() # 404 if missing; IsStaffOrReadOnly already ran
old_name = book.cover.name
if request.method == "DELETE":
book.cover.delete(save=True) # removes the file and clears the field
return Response(status=status.HTTP_204_NO_CONTENT)
serializer = BookCoverSerializer(book, data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
if old_name:
book.cover.storage.delete(old_name) # Django never deletes old files for you
return Response(self.get_serializer(self.get_object()).data)The router turns this into /api/books/<id>/cover/. The ViewSet's IsStaffOrReadOnly applies, so only staff can POST or DELETE. MultiPartParser accepts only multipart/form-data, the format browsers use for files. Replacing a cover deletes the old file, because Django leaves orphaned files on disk otherwise.
In development, Django can serve the files too. At the end of config/urls.py (import settings and static at the top):
from django.conf import settings
from django.conf.urls.static import static
# Development only: static() returns [] when DEBUG is False
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)Step 6: test with curl
Log in as Priya with the cookie jar, exactly as in the auth lesson, then upload real and fake files. -F sends multipart/form-data, and @ means "read this file":
curl -b jar.txt -H "X-CSRFToken: $TOKEN" -F "cover=@swami-cover.jpg" http://127.0.0.1:8000/api/books/1/cover/{"id":1,"title":"Swami and Friends","author":1,"author_name":"R. K. Narayan","published_year":1935,"summary":"A schoolboy's adventures in the town of Malgudi.","cover":"http://127.0.0.1:8000/media/covers/7b70d0e2a9de4e2cbcacb1f2da7524a6.jpg","average_rating":4.5,"review_count":2,"created_at":"2026-11-16T09:00:00+05:30"}The cover is a full URL with the random name. Now the bad files, each sent the same way: a text file called notes.jpg, a valid GIF, a 5.9 MB PNG, a 4000-pixel-wide banner, a form with no file, and a JSON body:
{"cover":["Upload a valid image. The file you uploaded was either not an image or a corrupted image."]}
{"cover":["Use a JPEG, PNG or WebP image."]}
{"cover":["The cover must be 2 MB or smaller."]}
{"cover":["The cover must be at most 3000 pixels wide and high."]}
{"cover":["No file was submitted."]}
{"detail":"Unsupported media type \"application/json\" in request."}The first five are 400 and the last is 415. As Kabir, the same upload gets {"detail":"You do not have permission to perform this action."} (403). Uploading two covers for Godaan in a row left only the newer file in media/covers, and DELETE /api/books/3/cover/ returned 204, removed the file and set "cover": null. Opening the image URL shows the headers Django adds:
HTTP/1.1 200 OK Content-Type: image/jpeg Content-Length: 14048 X-Content-Type-Options: nosniff
(Other headers are left out.) nosniff tells the browser to trust the declared type and never guess, an important guard for user files.
Step 7: upload from React
First let Vite pass /media to Django as well. Add a second entry to server.proxy in vite.config.js, with the same object form as /api:
"/media": {
target: "http://127.0.0.1:8000",
changeOrigin: false,
},Because changeOrigin: false keeps the browser's Host header, DRF now builds cover URLs such as http://localhost:5173/media/covers/... for requests that come through Vite. Our curl check of /api/books/1/ through port 5173 returned exactly that.
The form sends a FormData object, the browser's built-in way to build a multipart body. apiFetch only sets Content-Type: application/json when the body is a string, so for FormData it sets nothing, and the browser writes the correct header itself, including the boundary, a random marker that separates the parts. See it for yourself:
import { useEffect, useState } from "react";
import { createRoot } from "react-dom/client";
function Inspect() {
const [text, setText] = useState("");
useEffect(() => {
const body = new FormData();
body.append("cover", new File(["(image bytes here)"], "swami.jpg", { type: "image/jpeg" }));
const request = new Request("https://bookshelf.example.in/api/books/1/cover/", { method: "POST", body });
request.text().then((raw) => setText(`Content-Type: ${request.headers.get("content-type")}\n\n${raw}`));
}, []);
return <pre style={{ whiteSpace: "pre-wrap" }}>{text}</pre>;
}
createRoot(document.getElementById("root")).render(<Inspect />);You will see multipart/form-data; boundary=----WebKitFormBoundary... (the exact marker differs per browser and run), then the part with name="cover" and filename="swami.jpg". If you set Content-Type: multipart/form-data by hand, the boundary is missing. We tried it with curl and Django answered {"detail":"Multipart form parse error - Invalid boundary in multipart: None"}.
Now create src/components/CoverUpload.jsx:
import { useEffect, useState } from "react";
import { apiFetch } from "../api/client.js";
import { splitErrors } from "../utils/errors.js";
import FieldError from "./FieldError.jsx";
const MAX_BYTES = 2 * 1024 * 1024; // same limits as BookCoverSerializer
const TYPES = ["image/jpeg", "image/png", "image/webp"];
const NO_ERRORS = { fields: {}, form: [] };
// Quick checks for comfort. Django opens the file with Pillow and decides.
function checkFile(file) {
if (!TYPES.includes(file.type)) return "Use a JPEG, PNG or WebP image.";
if (file.size > MAX_BYTES) return "The cover must be 2 MB or smaller.";
return null;
}
export default function CoverUpload({ book, onSaved }) {
const [file, setFile] = useState(null);
const [preview, setPreview] = useState(null);
const [errors, setErrors] = useState(NO_ERRORS);
const [saving, setSaving] = useState(false);
// Free the old preview's memory when it is replaced or the form goes away
useEffect(() => {
return () => {
if (preview) URL.revokeObjectURL(preview);
};
}, [preview]);
function handleChange(event) {
const chosen = event.target.files[0] ?? null;
const problem = chosen && checkFile(chosen);
const ok = chosen && !problem;
setErrors(problem ? { fields: { cover: [problem] }, form: [] } : NO_ERRORS);
setFile(ok ? chosen : null);
setPreview(ok ? URL.createObjectURL(chosen) : null); // a local blob: URL, no upload yet
}
async function handleSubmit(event) {
event.preventDefault();
if (!file) return;
const body = new FormData();
body.append("cover", file); // the field name Django expects
setSaving(true);
try {
await apiFetch(`/books/${book.id}/cover/`, { method: "POST", body });
setFile(null);
setPreview(null);
event.target.reset(); // clear the file input
onSaved();
} catch (error) {
setErrors(splitErrors(error, ["cover"]));
} finally {
setSaving(false);
}
}
return (
<form className="cover-upload" onSubmit={handleSubmit}>
<h2>Cover image</h2>
{errors.form.length > 0 && <p role="alert" className="form-errors">{errors.form.join(" ")}</p>}
<label htmlFor="cover">Choose a JPEG, PNG or WebP file (up to 2 MB)</label>
<input id="cover" type="file" accept="image/jpeg,image/png,image/webp" onChange={handleChange} />
<FieldError messages={errors.fields.cover} />
{preview && <img src={preview} alt="Preview of the new cover" width="120" />}
<button type="submit" disabled={!file || saving}>
{saving ? "Uploading..." : "Upload cover"}
</button>
</form>
);
}URL.createObjectURL(file) gives a temporary blob: address for a file that is still on the user's computer, so the preview appears before anything is uploaded. Each one holds memory until it is revoked, which the effect's cleanup does. accept only filters the file picker; users can still choose "All files", which is why checkFile exists, and why Django checks again.
Show the form to staff only in BookDetail: {user?.is_staff && <CoverUpload book={book.data} onSaved={book.reload} />}. Show the cover itself above the title with alt text such as "Cover of Godaan", and on each BookCard with alt="" and loading="lazy". The empty alt is deliberate on cards: the title is right next to the image, so a screen reader would only repeat it. Always give width and height so the page does not jump while images load.
We tested it in headless Chrome as Priya on /books/3. Choosing the 5.9 MB PNG showed "The cover must be 2 MB or smaller." at once, with no request. Choosing notes.jpg passed the browser check (its name says JPEG) but Django replied "Upload a valid image. The file you uploaded was either not an image or a corrupted image." under the field. Choosing a real 200x300 PNG uploaded it, and the page then showed the image Cover of Godaan at 200x300 from http://localhost:5173/media/covers/af0a95e15da04b20985c9695e5663158.png.
Here is the file check and preview on its own. Pick any image, then a large photo or a PDF:
import { useEffect, useState } from "react";
import { createRoot } from "react-dom/client";
const TYPES = ["image/jpeg", "image/png", "image/webp"];
const MAX_BYTES = 2 * 1024 * 1024;
const size = new Intl.NumberFormat("en-IN", { maximumFractionDigits: 1 });
function Picker() {
const [info, setInfo] = useState(null);
const [preview, setPreview] = useState(null);
useEffect(() => () => { if (preview) URL.revokeObjectURL(preview); }, [preview]);
function handleChange(e) {
const file = e.target.files[0];
if (!file) return;
let problem = null;
if (!TYPES.includes(file.type)) problem = "Use a JPEG, PNG or WebP image.";
else if (file.size > MAX_BYTES) problem = "The cover must be 2 MB or smaller.";
setInfo({ name: file.name, type: file.type || "(unknown)", kb: size.format(file.size / 1024), problem });
setPreview(problem ? null : URL.createObjectURL(file));
}
return (
<main>
<label>Cover <input type="file" accept="image/jpeg,image/png,image/webp" onChange={handleChange} /></label>
{info && <p>{info.name}, {info.type}, {info.kb} KB</p>}
{info?.problem && <p role="alert" style={{ color: "#b00020" }}>{info.problem}</p>}
{preview && <img src={preview} alt="Preview of the chosen cover" width="120" />}
</main>
);
}
createRoot(document.getElementById("root")).render(<Picker />);Serving media in production
static() serves files only while DEBUG is on. We imported config.urls with each setting and listed the media patterns:
DEBUG = True -> ['^media/(?P<path>.*)$'] DEBUG = False -> []
So on a real server, Django serves no uploads, on purpose: a Python process is a slow way to send image bytes. Choose one of these, as Deploying Django + React shows in full:
- The web server serves
MEDIA_ROOTdirectly. For example, Nginx with alocation /media/block that points at/srv/bookshelf/media/, plusclient_max_body_sizea little above your 2 MB limit, so huge uploads are rejected before they reach Django. - Object storage (an S3-compatible bucket) through the
django-storagespackage and Django'sSTORAGESsetting. Uploads then survive server rebuilds and can sit behind a CDN.
Common mistakes
- Setting
Content-Typeyourself for FormData. The boundary goes missing and Django cannot parse the body. - Keeping the user's file name. Use a random name from
upload_to. - Checking only the extension or
file.type. Both are chosen by the uploader; Pillow checks the content. - Forgetting old files. Replacing or clearing a
FileFieldleaves the old file on disk unless you delete it. - Media inside the code folder in production. A redeploy can wipe it. Use a separate folder or object storage.
Interview questions
1. What is the difference between static files and media files in Django?
Static files are part of the code, such as CSS and JavaScript, and change only when you deploy. Media files are uploaded by users while the site runs. They are untrusted, are not kept in Git, and live in MEDIA_ROOT, often outside the project folder or in object storage.
2. How do you validate an image upload safely?
Open it with Pillow (Django's ImageField does this) and check the format it detects, not the name or Content-Type. Limit the file size and the pixel dimensions, rename it to a random name, and serve it with nosniff. Never accept formats that can contain scripts, such as SVG, for user images.
3. Why should React not set the Content-Type header when sending FormData?
The browser must write multipart/form-data together with a generated boundary string that separates the parts. A hand-written header lacks the boundary, so the server cannot split the body.
4. How are media files served in development and production?
In development, django.conf.urls.static.static() adds a view that serves MEDIA_ROOT, and only while DEBUG is on. In production, a web server such as Nginx or an object storage service with a CDN serves them, and Django only stores the files and their paths.
Key points
- Install Pillow for
ImageField; Django refuses to start without it. MEDIA_ROOTis where uploads live on disk (outside the code in production);MEDIA_URLis their URL prefix.- Rename uploads with
upload_to, check the real format, bytes and pixels in the serializer, and delete replaced files. - A staff-only
@actionwithMultiPartParserkeeps uploads separate from JSON edits. - React sends
FormDatawithout aContent-Typeheader, previews withURL.createObjectURL, and repeats the checks only for comfort. static()serves media only withDEBUGon; production uses the web server or object storage.
Exercise
Add a "Remove cover" button to CoverUpload for books that have a cover. It should ask for confirmation in the page itself (a second "Yes, remove it" button, not window.confirm), send DELETE /api/books/<id>/cover/, and reload the book. Show any error in the form's alert box.
Show solution
// Inside CoverUpload
const [confirming, setConfirming] = useState(false);
async function handleRemove() {
setSaving(true);
try {
await apiFetch(`/books/${book.id}/cover/`, { method: "DELETE" });
setConfirming(false);
onSaved();
} catch (error) {
setErrors(splitErrors(error, ["cover"]));
} finally {
setSaving(false);
}
}
// In the JSX, after the upload button
{book.cover && !confirming && (
<button type="button" onClick={() => setConfirming(true)}>Remove cover</button>
)}
{confirming && (
<p>
Remove this cover?{" "}
<button type="button" onClick={handleRemove} disabled={saving}>Yes, remove it</button>{" "}
<button type="button" onClick={() => setConfirming(false)}>Cancel</button>
</p>
)}DELETE is an unsafe method, so apiFetch adds the CSRF header by itself. The API answers 204 with no body, which apiFetch returns as null, and onSaved() reloads the book, which now has "cover": null, so the button disappears.
Quick Quiz
1. Why does BookShelf rename uploaded covers to a random name?
A random name reveals nothing and cannot be guessed.
2. A user uploads notes.jpg, which is really a text file. Which part rejects it?
The name and browser type said JPEG; only opening the content reveals the truth.
3. What happens to /media/ URLs when DEBUG is False?
static() returns an empty list outside debug mode.
4. What is wrong with apiFetch(url, { method: "POST", body: formData, headers: { "Content-Type": "multipart/form-data" } })?
Let the browser set the multipart header with its boundary.
Learn Django + React with a mentor
Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
