简体   繁体   中英

django serving static files/ angularJS app

I have written a rest-API using Django-rest-framework with an angularjs app as the frontend. I am also using gulp to build a compressed version of my angularjs app and it outputs this in the static files directory of my django app. I tried using the django templateview but this gives a console error as such:

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

these 2 files are both valid javascript files. this is my urls file:

from django.views.generic import TemplateView

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

and these are my static files and template settings:

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',
            ],
        },
    },
]

my angular app is located in static/eventshop and the links in the index.html are relative urls (so without the STATIC_URL prefix).

Why is it giving me this error and/or what is the best way to serve a 'static' angular app in django?

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

You own answer was helpful but I found I had to include WHITENOISE_INDEX_FILE = True to my settings.py to get it to work - what I ended up using:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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