[英]Serving static files from root directory in Django
我有應用程序級別的 static 文件並希望提供全局 static 文件,例如 JQuery,我的項目結構是這樣的:
mysite
├───dashboard
│ ├───migrations
│ ├───static
│ │ └───dashboard
│ │ ├───css
│ │ ├───img
│ │ └───js
│ └───templates
│ └───dashboard
├───etc
├───static
│ └───js
| └───jquery.min.js
└───mysite
我添加了 django 文檔,以便 settings.py 看起來
STATIC_ROOT = ""
STATIC_URL = '/static/'
STATICFILES_DIR = [
os.path.join(BASE_DIR, "static"),
os.path.join("static"),
]
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
我的 urls.py 看起來像這樣
urlpatterns = [
path('admin/', admin.site.urls),
path("", include(dashboard.urls)),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
我的 INSTALLED_APPS 看起來像這樣
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
"dashboard",
]
當我嘗試從模板訪問它時,它會在 runserver 日志中返回響應代碼 404,
[09/Apr/2020 01:59:34] "GET /static/js/jquery.min.js HTTP/1.1" 404 1674
模板標簽是這樣的
{% load static %}
<script src="{% static 'js/jquery.min.js' %}"></script>
這是我的第一個 Django 項目,沒有遵循教程,任何幫助將不勝感激。 謝謝你
編輯:我能夠通過刪除STATIC_ROOT
設置來解決問題
You need to specify a prefix in front of one of the two directories named static
because Django will use the first static file it finds whose name matches, and if you had a static file with the same name in a different application, Django would be unable來區分它們。 我們需要能夠將 Django 指向正確的位置,確保這一點的最佳方法是對它們進行namespacing
。 也就是說,將這些 static 文件放在另一個以應用程序本身命名的目錄中。
您可以通過指定prefixes在 STATICFILES_DIRS 中命名 static 資產。 例如:
STATICFILES_DIR = [
("main", os.path.join(BASE_DIR, "static")),
os.path.join("static"),
]
接着:
<script src="{% static 'main/js/jquery.min.js' %}"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.