我在开发以及生产服务器上都安装了Django服务器。开发服务器加载了静态文件,但是生产服务器在加载时给出了404(尽管它呈现了URL)。
我已经使用了collectstatic方法来累积我的静态文件。
settings.py:
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
STATIC_URL = '/static/'
urls.py(main_project)
from django.contrib import admin
from django.urls import path, include
from django.conf import settings # new
from django.conf.urls.static import static # new
urlpatterns = [
path('', include('stock_management.urls', namespace='stock_management')),
path('auth/', include('django.contrib.auth.urls')),
path('admin/', admin.site.urls),
]
# if settings.DEBUG: # new
# urlpatterns += static(settings.STATIC_URL,
# document_root=settings.STATIC_ROOT)
# urlpatterns += static(settings.MEDIA_URL,
# document_root=settings.MEDIA_ROOT)
urls.py(应用程序:stock_management):
from django.urls import path, include
from .views import *
from django.conf import settings
app_name = 'stock_management'
urlpatterns = [
# Stock:
path('', stock_list, name='homepage'),
path('stock/', stock_list, name='stock_list'),
path('stock/add', stock_create_view, name='add_stock'),
path('stock/<pk>/edit', stock_edit, name='stock_edit'),
# Item:
path('items/', item_list, name='item_list'),
path('item/<pk>/edit', item_edit, name='item_edit'),
path('item/<pk>/delete', item_delete, name='item_delete'),
# API
path('api/items', item_list_API, name='item_list_API'),
# Gallery:
path('items/gallery', item_gallery, name='item_gallery'),
]
# if settings.DEBUG:
# # test mode
# from django.conf.urls.static import static
# urlpatterns += static(settings.STATIC_URL,
# document_root=settings.STATIC_ROOT)
# urlpatterns += static(settings.MEDIA_URL,
# document_root=settings.MEDIA_ROOT)
我也希望我的静态文件也可以加载到服务器中。
答案 0 :(得分:2)
在settings.py中设置DEBUG = False时,Django停止提供静态文件。您需要为静态文件配置一个像Nginx这样的Web服务器。
以下是有用的教程:https://www.digitalocean.com/community/tutorials/how-to-deploy-a-local-django-app-to-a-vps