Django 区分两种文件:static files(属于应用程序的资源——CSS、JavaScript、要发布的图像)和 media files(用户在运行时上传的文件——头像、文档)。它们处理方式不同,因为它们的来源和生命周期从根本上是不同的。
Static 文件——应用程序的资源
python
STATIC_URL =
STATICFILES_DIRS = [BASE_DIR / ]
STATIC_ROOT = BASE_DIR /
<!-- in templates -->
{% load static %}
<link rel="stylesheet" href="{% static 'css/style.css' %}">
<img src="{% static 'images/logo.png' %}">
Static 文件是代码库的一部分——CSS、JS、字体、设计图像。它们受版本控制,对所有用户相同,并从项目的 static 目录中提供。
python manage.py collectstatic
# gathers ALL static files (from your apps and STATICFILES_DIRS) into STATIC_ROOT,
# so a web server / CDN can serve them efficiently in production
在 production 中,collectstatic 将所有应用的 static 文件合并到一个目录(STATIC_ROOT)中,供 web 服务器或 CDN 提供——Django 在 production 中不自己提供这些文件。
# settings.py
MEDIA_URL = "/media/"
MEDIA_ROOT = BASE_DIR / "media" # where UPLOADED files are stored
# a model with an uploadable file
class Profile(models.Model):
avatar = models.ImageField(upload_to="avatars/") # stored under MEDIA_ROOT/avatars/
document = models.FileField(upload_to="docs/")
profile.avatar.url # the URL to access the uploaded file
Media 文件是用户在运行时通过 FileField/ImageField 上传的。它们是动态的、不受版本控制、并随着用户上传内容而增长。
Static files Media files
Source part of your code uploaded by users at runtime
Version control YES (committed) NO (user-generated, .gitignored)
Lifecycle fixed (changes with code) dynamic (grows continuously)
Examples CSS, JS, logos, fonts avatars, uploaded documents, photos
Settings STATIC_URL/ROOT/DIRS MEDIA_URL/ROOT
Production collectstatic + CDN/server stored on disk/cloud (S3), served carefully
✓ Static → serve via the web server (nginx) or a CDN (cached, fast)
✓ Media → store on cloud storage (S3) for scalability/persistence; in multi-server
setups, local disk doesn't work (files must be shared) → use S3/object storage
✓ Security → VALIDATE uploaded files (type, size); be careful serving user uploads
(a user could upload malicious content)
理解 static 和 media 的区别对于正确构建和适当部署 Django 应用程序都很重要,因为这两种文件类型具有根本不同的来源、生命周期和处理需求。Static 文件(应用程序自身的 CSS、JavaScript、图像、字体)是代码库的一部分,受版本控制,对所有人相同——通过 {% static %} 引用,并使用 collectstatic 为 production 中由 web 服务器或 CDN 提供而合并。Media 文件(通过 FileField/ImageField 的用户上传)是动态的、用户生成的内容,在运行时创建,不受版本控制,并持续增长。
混淆它们或错误配置其设置(STATIC_* vs MEDIA_*)是常见的