前言
管理静态文件(比如图片、JavaScript、CSS) | Django 文档 | Django (djangoproject.com)
内置视图 | Django 文档 | Django (djangoproject.com)
通用设置
项目.settings.py中
STATIC_URL = '/static/'
if DEBUG:
STATICFILES_DIRS = [
BASE_DIR / "static",
]
else:
STATIC_ROOT = BASE_DIR / "static"
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / "media
DEBUG开启
无需其它改动
DEBUG关闭
项目.urls.py中
from django.views.static import serve
from django.urls import path, include, re_path
from . import settings
if not settings.DEBUG:
urlpatterns += [
re_path(r'^media/(?P<path>.*)$', serve, {
'document_root': settings.MEDIA_ROOT,
}),
re_path(r'^static/(?P<path>.*)$', serve, {
'document_root': settings.STATIC_ROOT,
}),
]
部署静态文件
python manage.py collectstatic --noinput