起步

线上部署时因设置了 settings.DEBUG = False 会导致静态文件都是 404 的情况。主要原因是应为关闭DEBUG模式后,Django 便不提供静态文件服务了。

设置settings.py

STATIC_ROOT = os.path.join(BASE_DIR, 'static')

修改项目的urls.py

from django.contrib import admin
from django.urls import path
from django.urls import include, path,re_path
from django.views.static import serve

from django.conf import settings
from django.conf.urls.static import static


urlpatterns = [
    ...,
    re_path(r'^static/(?P<path>.*)$', serve, {'document_root': settings.STATIC_ROOT}),
]

执行django转移静态文件命令

python manage.py collectstatic