background :
Online deployment Django The project has been set settings.DEBUG = False It will cause static files to be 404 The situation of . The main reason is that it should be closed DEBUG After the model ,Django There is no static file service .
runserver Start of
If the operation is through runserver The way of command , That's easy , Start up runserver Add --insecure Options can force django Working with static files .
Start in other ways
But if it's through uwsgi or daphne When it starts , The way of adding options doesn't work . To solve this problem , We need to use the static file service manually , This method is recommended , Because it also supports runserver The way .
resolvent 1:
from django.urls import path, re_path, include
from django.views.static import serve
from django.conf import settings
urlpatterns += [
# Static file access method I :
re_path(r'^media/(?P<path>.*)$', serve, {"document_root": settings.MEDIA_ROOT}),
re_path(r'^static/(?P<path>.*)$', serve, {'document_root': settings.STATIC_ROOT, }),
]
resolvent 2:
# Routing method 2 for accessing pictures and static resources
from django.conf import settings
from django.conf.urls.static import static
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.STATIC_ROOT)