首页 > 解决方案 > Django 2.2 静态文件在生产中不起作用(DEBUG False)

问题描述

我正在制作一个新的 django 应用程序,用户可以在其中上传图像,然后它们可以显示在页面上。我已经阅读了大量的 django staticfiles 部署文档,但不明白为什么它们仍然不起作用。

我所有的图像都将转到它们应该在的位置,并且在我的模型 django 的管理员中具有通向图像的正确路径,但它只是无法正确加载。

我在 settings.py 中的设置:

STATIC_URL = '/static/'
STATIC_ROOT = 'static' # live cdn such as AWS S3

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static')
]

MEDIA_ROOT = os.path.join(STATIC_ROOT, 'media')
MEDIA_URL = '/img/'

我的目录:

|- src
    |- myproject
        |- settings.py, views.py, urls.py etc
    |- myapp
        |- views.py urls.py models.py forms.py etc
    |- static (this folder is empty and appeared after running collectstatic
    |- templates
    |- db.sqlite3
    |- manage.py
|- static (this folder is OUTSIDE src)
    |- admin
        |- django admin stuff
    |- media
        |- img
            |- myimage.png

在 myapp 的 models.py 中,imagefield upload_to = 'img/'

如果我处于调试模式并添加推荐的代码以使其工作:

if settings.DEBUG:
    from django.conf.urls.static import static

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

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

一切正常。这只是在调试模式下。我知道文档说这仅在调试模式下有效,但我还是尝试了。我正在尝试一切。

我一直在尝试解决这个问题,但我无法从任何人那里得到任何帮助,django 文档和其他 stackoverflow 问题/答案也没有任何帮助。

我感谢你的帮助!

注意:这是一个与我之前的问题不同的问题,请不要再次关闭它。尝试

标签: pythondjangodjango-staticfilesdjango-deployment

解决方案


|- src
    |- myproject
        |- settings.py, views.py, urls.py etc
        |- static # This is where your static files should be...
    |- myapp
        |- views.py urls.py models.py forms.py etc
    |- static # This is where all your static files will be collected and served from
    |- templates
    |- db.sqlite3
    |- manage.py

推荐阅读