【问题标题】:django static files when hosting in heroku在heroku中托管时的django静态文件
【发布时间】:2021-10-28 03:15:11
【问题描述】:

我的静态文件夹中有 excel 文件,我从中读取以获取一些数据,但是当我部署我的项目时这些文件不存在

这些是我配置静态文件的设置

STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / 'staticfiles'
STATICFILES_DIRS = [
    BASE_DIR / 'static'
]


STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

这就是我对他们的看法

from django.conf import settings
from django.templatetags.static import static
from django.contrib.staticfiles.storage import staticfiles_storage
from django.contrib.staticfiles.finders import find

def get_static(path):
    if settings.DEBUG:
        return find(path)
    else:
        return static(path)

def sport_news(request):
    path = 'excel\sport_update.xlsx'
    excel_data = excel(get_static(path))
    return render(request, 'news/news.html', {"excel_data":excel_data, 'type':'Sport News'})

【问题讨论】:

    标签: django heroku django-views django-staticfiles django-settings


    【解决方案1】:

    请检查你的 settings.py 但首先

    pip install whitenoise
    

    在中间件中

    'whitenoise.middleware.WhiteNoiseMiddleware',
    

    在底部

    STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
    

    然后你的主要项目 urls.py

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

    请确保您的 settings.py 中有一个静态 cdn 文件夹

    然后运行python manage.py collectstatic

    如果您完成了上述所有操作,但文件仍然没有,请确保该文件在静态 cdn 文件夹中,如果在完成所有步骤后没有再次推送代码,您就可以开始了

    如果事情仍然不适合你告诉我

    【讨论】:

    • 现在一切正常,问题是当我使用“\”给出路径时,由于某种原因它必须是“/”。
    猜你喜欢
    • 2011-08-06
    • 1970-01-01
    • 1970-01-01
    • 2014-04-24
    • 2023-03-20
    • 2015-07-08
    • 2011-11-28
    • 2012-05-05
    • 2015-11-06
    相关资源
    最近更新 更多