【问题标题】:django serving static files/ angularJS appdjango 服务静态文件/ angularJS 应用程序
【发布时间】:2016-04-06 06:21:12
【问题描述】:

我使用 Django-rest-framework 编写了一个 rest-API,并以 angularjs 应用程序作为前端。我还在使用 gulp 构建我的 angularjs 应用程序的压缩版本,并将其输出到我的 django 应用程序的静态文件目录中。我尝试使用 django 模板视图,但这会导致控制台错误:

vendor-001932f856.js:1 Uncaught SyntaxError: Unexpected token <
app-2d5e1cec88.js:1 Uncaught SyntaxError: Unexpected token <

这 2 个文件都是有效的 javascript 文件。这是我的网址文件:

from django.views.generic import TemplateView

urlpatterns = [
    url(r'^.*$',TemplateView.as_view(template_name="index.html")),
]

这些是我的静态文件和模板设置:

STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'

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

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

我的 Angular 应用程序位于 static/eventshop 中,并且 index.html 中的链接是相对 url(因此没有 STATIC_URL 前缀)。

为什么它给我这个错误和/或在 django 中提供“静态”角度应用程序的最佳方式是什么?

【问题讨论】:

  • 看起来更像是 JS 错误而不是 django 错误。如果它是未缩小的,它是否有效?

标签: javascript python angularjs django static


【解决方案1】:

使用 django whitenoise 并将 WHITENOISE_ROOT 路径设置为我的静态文件对我有用。

【讨论】:

    【解决方案2】:

    您自己的回答很有帮助,但我发现我必须在我的 settings.py 中包含 WHITENOISE_INDEX_FILE = True 才能使其工作 - 我最终使用的是:

    STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')#typical usage from docs
    STATIC_ROOT = os.path.join(BASE_DIR, 'static')#this in both your/my case
    STATIC_URL = '/static/'
    WHITENOISE_ROOT = os.path.join(BASE_DIR, 'static')#same as static_root
    STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"
    WHITENOISE_INDEX_FILE = True
    

    【讨论】:

      猜你喜欢
      • 2020-09-07
      • 2011-06-01
      • 2016-04-05
      • 2013-12-08
      • 2016-12-22
      • 2010-11-13
      • 2012-04-15
      • 2021-11-24
      • 1970-01-01
      相关资源
      最近更新 更多