【问题标题】:404 errors on static assets in Django/Vue appDjango/Vue 应用程序中静态资产的 404 错误
【发布时间】:2019-05-23 06:01:41
【问题描述】:

我试图关注 this article 将 Django/Vue 应用程序部署到 heroku。概述的步骤是:

  • 运行 npm build 以创建包含已构建文件的 /dist 目录
  • 到 settings.py 的 TEMPLATES = [...] 部分,添加 'DIRS':[os.path.join(BASE_DIR, 'dist')],
  • 添加STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'dist/static')],(也在settings.py中)
  • 编辑 django urls.py 文件以包含以下行:url(r'^$', TemplateView.as_view(template_name='index.html')),

此时我已经完成了所有这些事情,这是我清理过的 settings.py 文件:

"""
Django settings for bad_fortune_cookie project.

Generated by 'django-admin startproject' using Django 2.1.2.

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

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

import os
import dj_database_url
#from whitenoise.django import DjangoWhiteNoise
from rest_framework import *

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


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

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

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

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'bad_fortune_cookie',
    #'fortunes'
]

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

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


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



# Pagination

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10
}

# Password validation
# https://docs.djangoproject.com/en/2.1/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.1/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/2.1/howto/static-files/

STATIC_URL = '/static/'

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

但我的新文件仍然出现 404,即使在运行 collectstatic 之后:

我查看了一些看似相关的问题(有些问题比其他问题更相关),但尝试这两个答案中的具体解决方案并没有解决问题: Error 404 static files in django 2.0

Django Static Root 404 Error

感谢任何帮助,如果有帮助,repo 是here.

【问题讨论】:

    标签: python django heroku vue.js


    【解决方案1】:

    正如我在github 的实现中看到的那样,您需要像这样在项目中定义资产目录(从代码中复制粘贴):

    module.exports = {
        outputDir: 'dist',
        assetsDir: 'static',
        // baseUrl: IS_PRODUCTION
        // ? 'http://cdn123.com'
        // : '/',
        // For Production, replace set baseUrl to CDN
        // And set the CDN origin to `yourdomain.com/static`
        // Whitenoise will serve once to CDN which will then cache
        // and distribute
        devServer: {
          proxy: {
            '/api*': {
              // Forward frontend dev server request for /api to django dev server
              target: 'http://localhost:8000/',
            }
          }
        }
    }
    

    基本上这里发生的情况是,您的静态文件在根路径/ 中提供服务,但静态文件应在路径/static 中提供(即:<your server>/static/js/abc.js

    【讨论】:

    • 这对我不起作用。 assetsDirpublicPath 似乎都不会影响构建,并且请求仍然转到 /js/about.js 而不是 static/js/about.js... 我什至禁用了块拆分。
    • 不幸的是,现在这是一个(非常)旧的答案,我目前不在范围内。抱歉,暂时帮不了你。
    猜你喜欢
    • 1970-01-01
    • 2018-05-24
    • 2016-05-25
    • 2018-12-07
    • 2018-05-20
    • 2019-01-23
    • 2018-05-24
    • 2021-10-19
    • 1970-01-01
    相关资源
    最近更新 更多