【Django】django3 debug=false后静态文件丢失 您所在的位置:网站首页 Django引用css和js文件 【Django】django3 debug=false后静态文件丢失

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

2023-01-07 15:17| 来源: 网络整理| 查看: 265

项目场景

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 "", line 1006, in _gcd_import File "", line 983, in _find_and_load File "", line 967, in _find_and_load_unlocked File "", line 677, in _load_unlocked File "", line 728, in exec_module File "", line 219, in _call_with_frames_removed File "/Users/PycharmProjects/website/website/urls.py", line 27, in ] + 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.*)$', static.serve, {'document_root': settings.STATIC_ROOT}, name='static') ]

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



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有