我的Django生产网站上图片坏了,为什么?

0 投票
2 回答
501 浏览
提问于 2025-05-01 00:36

我刚刚在Heroku上发布了我的网站,但遇到了一个奇怪的问题,媒体图片无法显示。

这里是我在Heroku上的网站结构。
 -- app
    -- manage.py
    -- mysite
       -- settings
         -- __init__.py
         -- base.py
         -- production.py
    -- static
       -- media
          -- product
            -- images
              -- 
       -- static_dirs
       -- static_root

在我的app/mysite/settings/ init.py文件里

from .base import *
try:
    from .local import *
    live = False
except:
    live = True
if live:
    from .production import *

还有在我的base.py文件里

import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
STATIC_URL = '/static/'
MEDIA_URL = '/media/'    
MEDIA_ROOT = os.path.join(BASE_DIR, 'static', 'media')    
STATIC_ROOT = os.path.join(BASE_DIR, 'static', 'static_root')
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static', 'static_dirs'),
)    
TEMPLATE_DIRS = (
    os.path.join(BASE_DIR, 'templates'),
)    

以及在我的production.py文件里,我做了如下注释。

# Static asset configuration
# import os
# BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# STATIC_ROOT = 'staticfiles'
# STATIC_URL = '/static/'    
# STATICFILES_DIRS = (
# os.path.join(BASE_DIR, 'static'),
# )

最后,我启动了服务器,但页面上还是显示了破损的图片。

当我通过“谷歌检查元素”仔细查看图片时,我仍然能看到可能正确的路径,如下所示。

<img class="img-responsive" src="/media/products/images/aws.png">

但是当我查看我的/static/media/products/images/文件夹时,发现里面只有在开发阶段创建的图片,而不是我在生产网站上刚创建的图片。(aws.png)

作为一个刚入门的django开发者,找答案真的很困难,即使我搜索了几个小时。

请让我休息一下,感谢你们的帮助。

暂无标签

2 个回答

0

你需要在你的生产环境服务器上运行 collectstatic 命令。

0

Django在调试模式下只会提供静态文件。具体情况和解决办法可以在官方文档中找到,链接是:https://docs.djangoproject.com/en/1.4/howto/static-files/

撰写回答