1

我正在使用 Django 为天气应用程序创建一个项目,但我认为我的 Javascript 文件位于错误的位置。我把它放在一个静态文件夹中。但我收到控制台错误 GET http://127.0.0.1:8000/static/capstone/capstone.js net::ERR_ABORTED 404 (Not Found)

这是我的项目文件的设置方式。这个对吗?

在 settings.py 我也有:

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

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

在此处输入图像描述

4

2 回答 2

2

创建一个新文件夹capstone并将您的 capstone.js 移至其中。
因为默认情况下 Djangostatic在应用程序中使用一个文件夹,所以在你的情况下,你访问的是 http://localhost:8000/static/capstone/capstone.js 但实际链接是 http://localhost:8000/static/顶石.js

于 2021-05-15T21:30:15.790 回答
0

Your BASE_DIR by default points to the same directory that manage.py is in. If you haven't changed it then capstone.js is currently located in

os.path.join(BASE_DIR, 'capstone/static')

BUT django by default looks for a static folder inside each installed app so in your case STATCFILES_DIRS is redundant.

Make sure you have added the static files to your urls.py.

from django.conf import settings
from django.conf.urls.static import static

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

or

from django.contrib.staticfiles.urls import staticfiles_urlpatterns

urlpatterns = [
    # ...urls
]

# static content urls
urlpatterns += staticfiles_urlpatterns()

This is my best guess as to why you are getting a 404 error.

NB: if you have setup static urls then try

http://127.0.0.1:8000/static/capstone.js instead.

于 2021-05-15T21:14:31.623 回答