![](/img/trans.png)
[英]Django: Why are my static files not showing up and always giving me a 404 error when DEBUG=False?
[英]External CSS Stylesheet and Images not showing up in Django Web Application when DEBUG=False
我有一個基本的 Django Web 應用程序,該應用程序使用static/css
文件夾中的外部 CSS 樣式表,font-awesome-fonts 在static/fonts
文件夾中加載圖像media/images
每當我設置DEBUG = False
時,圖像和 CSS 樣式表都會被忽略,只顯示 HTML 模板。
我的目錄結構如下:
app/
├── myapp/
├── media/
├── static/
└── templates/
settings.py
BASE_DIR = Path(__file__).resolve().parent.parent
DEBUG = True
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, "templates/")],
'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',
],
},
},
]
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static/"),
)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
我發現了如何通過添加if
else
語句在主項目URLs.py
中顯示媒體,但即使我將+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
添加到urlpatterns[]
的末尾,它也沒有當DEBUG = False
時顯示。 我也嘗試添加static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
。
urls.py
from django.contrib import admin
from django.urls import include, path
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = [
path('', include('myapp.urls')),
path('admin/', admin.site.urls),
]
# Serving the media files in development mode
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
else:
urlpatterns += staticfiles_urlpatterns()
當 DEBUG=False 時,Django 不提供靜態數據。
您必須像為媒體一樣添加 URL 或以其他方式(前端或外部存儲)提供它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.