簡體   English   中英

在生產 Django-Heroku 中找不到媒體文件:返回 404 錯誤

[英]Media file not being found in production Django-Heroku: returns 404 error

我在 Djang 的媒體文件夾中有一些默認圖像。 但是,在我的網站上,我看不到正在顯示的圖像,並且出現 404 錯誤。

現在我的項目文件夾樹是(項目名稱是注冊):

register
-- live-static
---- static-root
---- media-root
------ defaults

我的媒體和靜態文件設置是:

STATIC_URL = '/static/'
STATICFILES_DIRS = [ 
    os.path.join(BASE_DIR, 'static')
]
STATIC_ROOT = os.path.join(BASE_DIR, 'live-static', 'static-root')

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'live-static', 'media-root')

STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'

在我的urls.pywsgi.py相同的文件夾中,我有:

urlpatterns = [ 
    """
    My other urls
    """ 
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT ) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

我的靜態文件已加載,服務器可以檢索它們,但是,我添加到media-root文件夾中的圖像由服務器返回 404 錯誤。 為什么會發生這種情況,因為我也已經設置了STATICFILES_STORAGE

這是我第一次部署 Heroku 時遇到的問題。 由於 Heroku 項目在 dynos 上運行,如果在一段時間內沒有請求,它們最終會進入睡眠狀態。 當測功機重啟時,它不會保存上傳的數據。 以下是 Heroku 部分信息的鏈接: https : //help.heroku.com/K1PPS2WM/why-are-my-file-uploads-missing-deleted

我最終做的是設置一個 Amazon S3 存儲桶來存儲這些文件。 Dennis Ivy 做了一個視頻來解釋如何做到這一點: https : //youtu.be/inQyZ7zFMHM

像這樣更新您的設置文件

無需更改任何其他內容

在 urls.py 中將 urlpatterns 更改為。 刪除 STATIC_ROOT 等

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

在 setting.py 這樣。 刪除其他文件設置,如 STATICFILES_STORAGE

MEDIA_URL = '/media/'
STATIC_URL = '/static/'



STATICFILES_DIRS = [
    os.path.join(BASE_DIR,'static')
]
#if your media folder is in public_html which contain the media file
MEDIA_ROOT = '/home/yourusername/public_html/media'
STATIC_ROOT = '/home/yourusername/public_html/static'

#if your media folder is in other_folder which contain the media file
MEDIA_ROOT = '/home/yourusername/other_folder /media'
STATIC_ROOT = '/home/yourusername/other_folder /static'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM