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


    问题描述:

    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

  • 相关阅读:
    JVM简单入门
    10 张图聊聊线程的生命周期和常用 APIs
    Spring Cloud实战 | 最八篇:Spring Cloud +Spring Security OAuth2+ Axios前后端分离模式下无感刷新实现JWT续期
    ueditor 插入视频代码解析
    CentOS下添加新硬盘并分区格式化的详细步骤
    Java 8 stream
    crontab命令详解
    计算机网络自顶向下学习杂记
    nginx安装
    js识别PC和H5
  • 原文地址:https://www.cnblogs.com/yaner2018/p/13365039.html
Copyright © 2020-2023  润新知