【Django】django3 debug=false后静态文件丢失

项目场景

django3.2 debug=false后静态文件丢失,无法加载页面的js文件和css文件


问题描述

前端页面控制台报错:

Refused to apply style from ‘’ because its MIME type (‘text/html’) is not a supported stylesheet MIME type, and strict MIME checking is enabled.

原因分析

Django的DEBUG设置为True,表示项目以调试方式运行,这种模式下程序出错后会在前端页面和后台报出对应错误,并且Django会自动搜索静态文件。
设置DEBUG=False后,Django不会自动搜索静态文件,此时需要在ALLOWED_HOSTS里面添加程序所在的机器ip才能正常访问,并且Django会认为当前环境是生产环境,不在代理静态文件,自然也不会去搜索静态文件,程序运行需要加载静态文件时便会报404。


解决方案

1.在settings.py中配置静态文件路径

settings.py

STATIC_URL = '/static/'
STATIC_ROOT = Path(BASE_DIR, '/static/')

2.在urls.py中设置静态文件的路由

urls.py 中导入设置路由需要的模块并设置静态文件的url路由。

方法一

urls.py

...
from django.conf import settings
from django.views import static

urlpatterns = [
    ...
]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

运行后未成功,报错TypeError: 'module' object is not callable

  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/Users/PycharmProjects/website/website/urls.py", line 27, in <module>
    ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
TypeError: 'module' object is not callable

方法二(推荐)

urls.py

...
from django.conf import settings
from django.views import static

urlpatterns = [
    ...
    path(r'^static/(?P<path>.*)$', static.serve, {'document_root': settings.STATIC_ROOT}, name='static')
]

运行后,成功加载静态文件

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值