Django加载的是静态文件,而不是从生产后台存储的映像



正如标题所说,在我将DEBUG更改为False之后,从管理面板上传的图像没有加载。然而,其他静态文件(如css文件和仅从HTML端加载的图像(可以正确地呈现。

urls.py

urlpatterns = [
path('admin/', admin.site.urls),
path('', include('marathon.urls', namespace='homepage')),
path('accounts/', include('allauth.urls')),
path('logout', LogoutView.as_view(), name='logout'),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

渲染图像的html文件

<div class="js-billboard">
{% for slide in slider %}
<div class="billboard__item">
<figure><img src="{{ slide.image.url }}" alt="Mountain Marathon"></figure>
<div class="billboard__detail">
<div class="grid-container">
<div class="grid-x grid-padding-x">
<div class="col-12 cell">
<h2>{{ slide.title }}</h2>
<p><span>{{ slide.description }}</span></p>
<a href="{{ slide.link }}" class="button">{{ slide.link_title }}</a>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
</div>

我假设您的项目urls.py中有以下代码行

if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

请注意,媒体URLstatic(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)只有在DEBUG=True的情况下才会添加到您的URL模式列表中。Django在Production或DEBUG=False中不提供媒体文件

我建议使用在线存储API,如AWS3、cloudinary甚至firebase。无论是DEBUG=True还是DEBUG=False,它们都提供了服务媒体文件的能力。

if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root = settings.STATIC_ROOT)

将其添加到您的主urls.py文件夹中,并在您的主项目和设置.py 中创建一个文件夹名称staic-cdn

STATIC_CDN = BASE_DIR / 'static_cdn'
and in bottom 
STATIC_ROOT = STATIC_CDN
# MEDIA
MEDIA_ROOT = MEDIA_DIR
MEDIA_URL = '/media/'
and then run 
python manage.py collectstatic 

在您的终端中,它将在您的静态cdn文件夹中创建您的静态文件的副本,因为基于云的存储在您的cdn文件夹中将查找您的静态或媒体文件并确保安装枕头

告诉我如果你仍然得到错误