問題描述:
Django開發網頁在 Debug=True 模式下可以正常訪問時,切換為False后,頁面格式就亂了,即無法請求到靜態資源了
解決方法:
第一種:
1、設置項目 settings.py
增加 STATIC_ROOT
修改 STATICFILES_DIRS
1 STATIC_URL = '/static/' 2 STATICFILES_DIRS = [ 3 os.path.join(BASE_DIR,"/static/") ##增加/,原來是:os.path.join(BASE_DIR,"static") 4 ] 5 #debug改為false后新增 6 STATIC_ROOT = 'static'# 新增行
2、配置 urls
導入 static、settings、views
配置 static路徑
配置異常頁面
1 from django.urls import path 2 from django.conf.urls import url 3 from .views import * 4 #以下是將debug改為False后需要加入的 5 #from django.conf.urls import url 6 from django.views import static 7 from django.conf import settings 8 from . import views 9 10 11 app_name = 'appname' 12 urlpatterns = [ 13 path('', login, name='login'), 14 path('index/', index, name='index'), 15 path('archives/<int:year>/<int:month>/',archive, name='archive'), 16 path('platforms/<str:id>/',platform, name='platform'), 17 18 ...... 19 20 21 #增加處理識別靜態資源 22 url(r'^static/(?P<path>.*)$', static.serve, {'document_root': settings.STATIC_ROOT}, name='static'), 23 24 ] 25 26 27 28 # 配置異常頁面 29 handler403 = views.page_permission_denied 30 handler404 = views.page_not_found 31 handler500 = views.page_inter_error
如果設置后,登陸admin后台時還是會出現頁面混亂,最好是在項目總路由 urls.py下配置static路徑!
3、設置 views.py
1 def page_permission_denied(request): 2 from django.shortcuts import render 3 return render(request, '403.html') 4 5 6 def page_not_found(request): 7 from django.shortcuts import render 8 return render(request, '404.html') 9 10 11 def page_inter_error(request): 12 from django.shortcuts import render 13 return render(request, '500.html')
這種方式修改后,發現日期控件沒了???
另一種方式好像更簡單:
啟動服務時添加參數 --insecure (不穩定)
python manage.py runserver --insecure 0.0.0.0:8000