【问题标题】:Django images in static folder can not show on Heroku project静态文件夹中的 Django 图像无法在 Heroku 项目中显示
【发布时间】:2021-10-17 07:02:08
【问题描述】:

我在 Heroku 上部署了我的应用程序。

但我的静态文件夹中的图像不会显示出来。


在我的本地环境中,这里是截图

但是在项目上,图片加载失败


这里是多个相关文件中的代码。

settings.py

from pathlib import Path
import os


# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # additional django
    'django.contrib.sites',
    'django.contrib.sitemaps',

    'article',
    'taggit',
    'crispy_forms',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'blog.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'article.context_processors.common_context'
            ],
        },
    },
]

WSGI_APPLICATION = 'blog.wsgi.application'

# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/

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


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

# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

CRISPY_TEMPLATE_PACK = 'bootstrap4'

SITE_ID = 1


if os.environ.get('DJANGO_PRODUCTION'):

    import dj_database_url

    DATABASES = {
        'default': dj_database_url.config(),
    }
    SECRET_KEY = os.environ.get('SECRET_KEY')

    # Allow all host headers.
    ALLOWED_HOSTS = [
        'ycy-blog.herokuapp.com',
        'www.ycyangtw.com',
    ]

    # Turn off DEBUG mode.
    DEBUG = (os.environ.get('DEBUG_VALUE') == 'True')

urls.py

​​>
from django.contrib import admin, sitemaps
from django.urls import path
from django.urls.conf import include
from django.contrib.sitemaps.views import sitemap
from django.conf.urls.static import static
from django.conf import settings
from article.sitemaps import PostSitemap

sitemaps = {
    'posts': PostSitemap,
}


urlpatterns = [
    path('admin_page/', admin.site.urls),
    path('', include('article.urls', namespace='article')),


    path(
        'sitemap.xml', sitemap, {'sitemaps': sitemaps},
        name='django.contrib.sitemaps.views.sitemap'
    ),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) \
    + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

test_static.html

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>
        hello
    </h1>
    <img src="{% static 'article/cover/fed-fund-rate_cover.jpg' %}">
</body>
</html>

我在stackoverflow上遇到过很多类似的问题,

但还是解决不了

到底发生了什么?

感谢帮助

【问题讨论】:

  • 您是否创建了collectstaticfiles 并在settings.py 中配置了collectstatic 文件?
  • 嗨,mhhabib。你的意思是STATIC_ROOT 还是别的什么? STATIC_ROOT 已经在 settings.py 中了。
  • 在部署到 Heroku 之前,您的静态文件应该像静态文件一样被收集到 python manage.py collectstatic
  • 刚试过python manage.py collectstatic再推,还是不行:(.Tks

标签: django image heroku static


【解决方案1】:

你收集静态文件了吗?

尝试运行:

heroku run python manage.py collectstatic --dry-run --noinput

【讨论】:

  • 嗨马尔米克。刚试了下,还是不行。谢了。
  • 点需要检查,安装whitenoise,正确配置STATIC_ROOT,不要忘记添加中间件'whitenoise.middleware.WhiteNoiseMiddleware',谢谢。
  • 安装whitelnoise,配置STATIC_ROOT和添加中间件都完成了,顺便说一句,STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')对heroku来说是正确的吧?
  • 实际上有一些缓存。试试看这个feed
  • tks,我确定图像已经成功上传,它在推送到 Heroku 期间显示消息。还是您认为我设置了错误的路径?
【解决方案2】:

在你的 urls.py 中使用这个

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

而不是

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

然后运行 ​​py manage.py collectstatic 然后推送到 heroku master

【讨论】:

  • 嗨,Shreyash。我之前都试过了。他们显示了相同的结果。问题已解决。谢了。
【解决方案3】:

简要总结。

由于图像文件夹的名称包含在.gitignore 文件中,即cover,我没有注意到这一点。这些文件实际上并未上传。

我使用heroku run bash 检查我的项目结构,然后发现cover 文件夹不会以任何方式显示。然后我检查.gitignore 以弄清楚到底发生了什么。

谢谢大家。

【讨论】:

    猜你喜欢
    • 2020-06-21
    • 2018-11-07
    • 2017-07-09
    • 2012-07-02
    • 1970-01-01
    • 1970-01-01
    • 2019-05-30
    • 2020-04-02
    • 1970-01-01
    相关资源
    最近更新 更多