Django DEBUG=False不提供媒体文件、缩略图或缩略图

k2fxgqgv  于 2023-03-31  发布在  Go
关注(0)|答案(1)|浏览(213)

我正在开发一个应用程序,当设置为生产模式(DEBUG=False)时,不加载图像缩略图,当DEBUG=True正常加载和显示时,静态文件也在生产中正常加载,当命令python3 manage. py collectstatic
Settings.py

STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

urls.py

...
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
...
noj0wjuj

noj0wjuj1#

找到了答案

from django.urls import re_path
    from django.conf import settings
    from django.conf.urls.static import static
    from django.views.static import serve

    urlpatterns = [

        re_path(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}),

]

    # urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

此re_path函数可以请求www.example.com中的所有MEDIA_ROOT文件settings.py

相关问题