首页 > 其他 > 详细

解决Django设置 DEBUG=False后静态文件无法加载的问题

时间:2020-07-23 15:41:19      阅读:58      评论:0      收藏:0      [点我收藏+]

问题描述:

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、配置 app 下的 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

 

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)

 

解决Django设置 DEBUG=False后静态文件无法加载的问题

原文:https://www.cnblogs.com/yaner2018/p/13365039.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!