简体   繁体   English

Django和Heroku控制台中的静态文件出现404错误

[英]404 error for static files in console with Django and Heroku

I am able to run collectstatic fine when I push to Heroku. 当我推送到Heroku时,我可以运行collectstatic。 The problem now is I that I'm not sure how to reference them when they're stored on the server. 现在的问题是我不确定将它们存储在服务器上时如何引用它们。

For example for my stylesheets I get a 404 error: <link rel="stylesheet" type="text/css" href="/static/bower_components/bootstrap-material-design/dist/css/material.css" /> 例如对于我的样式表,我收到404错误: <link rel="stylesheet" type="text/css" href="/static/bower_components/bootstrap-material-design/dist/css/material.css" />

This is the URL in the console that is causing the 404: GET https://tixblast-membership.herokuapp.com/static/bower_components/bootstrap-material-design/dist/css/material.css net::ERR_ABORTED 404 (Not Found) 这是导致404的控制台中的URL: GET https://tixblast-membership.herokuapp.com/static/bower_components/bootstrap-material-design/dist/css/material.css net::ERR_ABORTED 404 (Not Found)

What part of my settings to I alter to make sure I look in the right place? 我需要更改设置的哪一部分以确保在正确的位置显示? I ran heroku run python manage.py findstatic --verbosity 2 css/styles.css to show where it was looking for static files and it returned: /app/.heroku/python/lib/python3.7/site-packages/django/contrib/admin/static /app/.heroku/python/lib/python3.7/site-packages/rest_framework/static 我运行heroku run python manage.py findstatic --verbosity 2 css/styles.css以显示它在哪里寻找静态文件,并且返回了: /app/.heroku/python/lib/python3.7/site-packages/django/contrib/admin/static /app/.heroku/python/lib/python3.7/site-packages/rest_framework/static

So do I need to include one of the above directories in my settings? 因此,是否需要在设置中包括上述目录之一?

I assumed that after I got collectstatic working I'd be fine, here is my settings.py: 我以为我在进行静电收集工作后会没事的,这是我的settings.py:

"""
Django settings for thinkster_django_angular_boilerplate project.

For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
import django_heroku

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


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = *****

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.environ.get('DEBUG', True)

TEMPLATE_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',
    'rest_framework',
    'authentication'
)

MIDDLEWARE_CLASSES = (
    'whitenoise.middleware.WhiteNoiseMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'thinkster_django_angular_boilerplate.urls'

WSGI_APPLICATION = 'thinkster_django_angular_boilerplate.wsgi.application'


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

import dj_database_url

DATABASES = {
    'default': dj_database_url.config(
        default='sqlite:///' + os.path.join(BASE_DIR, 'db.sqlite3')
    )
}

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

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


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

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

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(BASE_DIR,'static'),
        ],
        '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',
            ],
        },
    },
]

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

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    #'compressor.finders.CompressorFinder',
)

COMPRESS_ENABLED = os.environ.get('COMPRESS_ENABLED', False)

TEMPLATE_DIRS = (
    os.path.join(BASE_DIR, 'static'),

)

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.SessionAuthentication',
    )
}

# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

# Allow all host headers
ALLOWED_HOSTS = ['*']
AUTH_USER_MODEL = 'authentication.Account'

django_heroku.settings(locals())

edit: 编辑:

My stylesheet: 我的样式表:

{% load staticfiles %}


<link rel="stylesheet" type="text/css" href="{% static 'bower_components/bootstrap/dist/css/bootstrap.css' %}" />
<link rel="stylesheet" type="text/css" href="{% static 'bower_components/bootstrap-material-design/dist/css/material.css' %}" />
<link rel="stylesheet" type="text/css" href="{% static 'bower_components/bootstrap-material-design/dist/css/ripples.min.css' %}" />
<link rel="stylesheet" type="text/css" href="{% static 'bower_components/ngDialog/css/ngDialog.css' %}" />
<link rel="stylesheet" type="text/css" href="{% static 'bower_components/ngDialog/css/ngDialog-theme-default.css' %}" />

<link rel="stylesheet" type="text/css" href="{% static 'lib/snackbarjs/snackbar.min.css' %}" />

<link rel="stylesheet" type="text/css" href="{% static 'stylesheets/styles.css' %}" />

edit2: EDIT2:

file structure where my app is located, its in the same folder as my settings.py. 我的应用程序所在的文件结构,与我的settings.py位于同一文件夹中。 Which is the only way heroku would notice it: 这是heroku注意到它的唯一方法:

└───static ├───bower_components │ ├───angular │ ├───angular-cookies │ ├───angular-route │ ├───bootstrap │ │ ├───dist │ │ │ ├───css │ │ │ ├───fonts │ │ │ └───js │ │ ├───fonts │ │ ├───grunt │ │ ├───js │ │ ├───less │ │ │ └───mixins │ │ └───nuget │ ├───bootstrap-material-design │ │ ├───dist │ │ │ ├───css │ │ │ ├───fonts │ │ │ └───js │ │ ├───fonts │ │ ├───less │ │ ├───sass │ │ └───scripts │ ├───jquery │ │ ├───dist │ │ └───src │ │ ├───ajax │ │ │ └───var │ │ ├───attributes │ │ ├───core │ │ │ └───var │ │ ├───css │ │ │ └───var │ │ ├───data │ │ │ └───var │ │ ├───effects │ │ ├───event │ │ ├───exports │ │ ├───manipulation │ │ │ └───var │ │ ├───queue │ │ ├───sizzle │ │ │ └───dist │ │ ├───traversing │ │ │ └───var │ │ └───var │ ├───ngDialog │ │ ├───css │ │ └───js │ └───underscore ├───javascripts │ └───authentication │ ├───controllers │ │ └───New folder │ └───services └───lib └───snackbarjs

edit 3: 编辑3:

This is where django is looking for the templates according to the error screen: 这是django根据错误屏幕在寻找模板的地方:

Using engine django:

django.template.loaders.filesystem.Loader: /app/static/index.html (Source does not exist)
django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.7/site-packages/django/contrib/admin/templates/index.html (Source does not exist)
django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.7/site-packages/django/contrib/auth/templates/index.html (Source does not exist)
django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.7/site-packages/rest_framework/templates/index.html (Source does not exist)

Going off what works for me, try deleting STATICFILES_FINDERS setting. 不适合我的情况,请尝试删除STATICFILES_FINDERS设置。 I don't think this is necessary for serving static with whitenoise. 我认为这对于用白噪声提供静态服务不是必需的。 In any case I don't use it. 无论如何我都不使用它。 Also, instead of MIDDLEWARE_CLASSES I just have MIDDLEWARE. 另外,我只有MIDDLEWARE而不是MIDDLEWARE_CLASSES。 Other than those minor changes I would just say try running your app with Debug=False on your local server and see if you run into problems. 除了那些小的更改,我只想说尝试在本地服务器上使用Debug = False运行您的应用程序,看看是否遇到问题。

Try changing your BASE_DIR setting to: 尝试将BASE_DIR设置更改为:

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

You should not hardcode static files URLs in your template when using static-files Django app instead, try the following in order to set up the static-files properly. 相反,在使用静态文件Django应用时,您不应该在模板中对静态文件URL进行硬编码,请尝试以下操作以正确设置静态文件。

  • Make sure that django.contrib.staticfiles is included in your INSTALLED_APPS. 确保django.contrib.staticfiles包含在INSTALLED_APPS中。

  • In your settings file, define STATIC_URL 在您的设置文件中,定义STATIC_URL

example: 例:

STATIC_URL = '/static/'

In your templates, use the static template tag to build the URL for the given relative path using the configured STATICFILES_STORAGE : 在您的模板中,使用静态模板标记通过配置的STATICFILES_STORAGE为给定的相对路径构建URL:

{% load static %}
<img src="{% static "my_app/example.jpg" %}" alt="My image">

I fixed it, I added the NodeJS buildback to Heroku. 我修复了它,然后将NodeJS构造添加到了Heroku中。 That installed the bower_components in the right folder. 那将bower_components安装在正确的文件夹中。 I'm using Python and Angular so I had the buildpack for the former but not the latter. 我使用的是Python和Angular,所以我拥有前者的buildpack,但没有后者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM