无法从Heroku引用Django项目的静态文件

时间:2023-02-05 12:51:16

I am unable to load static files in production, whereas they work on local machine.

我无法在生产中加载静态文件,而它们在本地计算机上工作。

I have followed the steps in https://devcenter.heroku.com/articles/django-assets as well as the existing answers but I am not able to make it run. I am overlooking something and would like the community's assistance.

我已按照https://devcenter.heroku.com/articles/django-assets中的步骤以及现有答案进行操作,但我无法使其运行。我忽视了一些事情,希望得到社区的帮助。

Here is the partial settings.py:

这是局部settings.py:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

ALLOWED_HOSTS = ['tryml.herokuapp.com','localhost']


# Application definition

INSTALLED_APPS = [
    'web.apps.WebConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

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 = 'tryml.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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',
            ],
        },
    },
]

WSGI_APPLICATION = 'tryml.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/2.0/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',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

import dj_database_url
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)

STATIC_URL = '/static/'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'

Here is the wsgi.py file:

这是wsgi.py文件:

import os

from django.core.wsgi import get_wsgi_application
from whitenoise.django import DjangoWhiteNoise

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tryml.settings")

application = get_wsgi_application()
application = DjangoWhiteNoise(application)

Here is the html file trying to access the static content:

这是试图访问静态内容的html文件:

{% extends "web/base.html" %}
{% load static %}

{% block content %}

      <div>
        <img src="{% static 'web/img/target.jpg' %}" alt="Image could not be loaded"></img>
      </div>

{% endblock %}

Here is the project structure:

这是项目结构:

tryml
  --static
    --web
      --img
        --target.jpg
  --tryml
    --settings.py
    --wsgi.py
    --urls.py 
  --web(web app)
  --(urls,forms,templates,...)
  --manage.py
  --Procfile
  --requirements.txt
  --runtime.txt

One more observation, when I check the requests sent from my browser, it shows a 404 error for the static file(image) and says it tried to lookup here- ...herokuapp.com/static/web/img/target.jpg

还有一个观察,当我检查从我的浏览器发送的请求时,它显示静态文件(图像)的404错误,并说它试图在这里查找 - ... herokuapp.com/static/web/img/target.jpg

Shouldn't it refer from STATIC_ROOT(staticfiles/web/img/target)?

它不应该引用STATIC_ROOT(staticfiles / web / img / target)吗?

EDIT-- The collectstatic command runs when the code is pushed on heroku,and it shows a successful copy step into app/staticfiles. Still, static file is not loading.

编辑 - 当代码被推送到heroku时,collectstatic命令运行,并显示成功复制到app / staticfiles中的步骤。但是,静态文件仍未加载。

EDIT2--I ran the command python manage.py findstatic web/img/target.jpg as mentioned here: https://docs.djangoproject.com/en/2.0/ref/contrib/staticfiles/#findstatic

EDIT2 - 我运行了命令python manage.py findstatic web / img / target.jpg,如下所述:https://docs.djangoproject.com/en/2.0/ref/contrib/staticfiles/#findstatic

It returned the file location on local machine but on heroku, it says 'No matching file found for 'web/img/target.jpg'.' Why is it not being located even after a collectstatic command has run successfully? How does the production fetch of static files actually work? When I use {% static web/img/target.jpg %}, does it go to the STATIC_ROOT location to fetch it?

它返回了本地机器上的文件位置,但在heroku上,它显示'找不到'web / img / target.jpg'的匹配文件。为什么即使在collectstatic命令成功运行后它也没有找到?生产获取静态文件实际上如何工作?当我使用{%static web / img / target.jpg%}时,是否会转到STATIC_ROOT位置来获取它?

2 个解决方案

#1


0  

You have to serve the static file using nginx or you have to add path in urls py.

您必须使用nginx提供静态文件,或者必须在urls py中添加路径。

urlpatterns = [
            # ... the rest of your URLconf goes here ...
 ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

#2


0  

After doing 'find' on the remote heroku server from my machine, I came to know that the file is stored as 'target.JPG' and not 'target.jpg'.

在我的机器上远程heroku服务器上“查找”后,我发现文件存储为'target.JPG'而不是'target.jpg'。

I changed the access link accordingly in the template and it worked.

我在模板中相应地更改了访问链接并且它工作正常。

On the local machine, the CAPS do not seem to matter as I had already played around with them earlier.

在本地机器上,CAPS似乎并不重要,因为我之前已经玩过它们。

Also, my git push to heroku never really changed the filename to 'target.jpg' because it doesn't consider changes in the caps of the filename unless told to as mentioned here - Changing capitalization of filenames in Git

此外,我的git推送到heroku从未真正将文件名更改为'target.jpg',因为它不会考虑文件名大小写的更改,除非告知这里提到 - 更改Git中文件名的大小写

Thank You.

谢谢。

#1


0  

You have to serve the static file using nginx or you have to add path in urls py.

您必须使用nginx提供静态文件,或者必须在urls py中添加路径。

urlpatterns = [
            # ... the rest of your URLconf goes here ...
 ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

#2


0  

After doing 'find' on the remote heroku server from my machine, I came to know that the file is stored as 'target.JPG' and not 'target.jpg'.

在我的机器上远程heroku服务器上“查找”后,我发现文件存储为'target.JPG'而不是'target.jpg'。

I changed the access link accordingly in the template and it worked.

我在模板中相应地更改了访问链接并且它工作正常。

On the local machine, the CAPS do not seem to matter as I had already played around with them earlier.

在本地机器上,CAPS似乎并不重要,因为我之前已经玩过它们。

Also, my git push to heroku never really changed the filename to 'target.jpg' because it doesn't consider changes in the caps of the filename unless told to as mentioned here - Changing capitalization of filenames in Git

此外,我的git推送到heroku从未真正将文件名更改为'target.jpg',因为它不会考虑文件名大小写的更改,除非告知这里提到 - 更改Git中文件名的大小写

Thank You.

谢谢。