django无法导入静态文件问题解决方法

 1 import os
 2 
 3 
 4 def filecntin(currpath):
 5     # '''汇总当前目录下文件数'''
 6     return sum([len(files) for root, dirs, files in os.walk(currpath)])
 7 
 8 
 9 def dirstree(startpath):
10     # '''树形打印出目录结构'''
11     for root, dirs, files in os.walk(startpath):
12         # 获取当前目录下文件数
13         filecount = filecntin(root)
14         # 获取当前目录相对输入目录的层级关系,整数类型
15         level = root.replace(startpath, '').count(os.sep)
16         # 树形结构显示关键语句
17         # 根据目录的层级关系,重复显示'| '间隔符,
18         # 第一层 '| '
19         # 第二层 '| | '
20         # 第三层 '| | | '
21         # 依此类推...
22         # 在每一层结束时,合并输出 '|____'
23         indent = '| ' * 1 * level + '|____'
24         print('%s%s fileCount:%s' % (indent, os.path.split(root)[1], filecount))
25 
26 
27 if __name__ == '__main__':
28     path = r"D:\后台数据管理"
29     dirstree(path)

以上代码显示树形结构以及统计文件总数。

现象:django导入静态文件失败,图片无法正常显示,jquery无法导入

原因:django特殊的路径处理机制

解决方法:

1.修改setting.py

# setting.py

STATIC_URL = 'static/'  
STATIC_ROOT = os.path.join(BASE_DIR, 'static')  

2. 修改url.py

 1 from django.contrib import admin
 2 from django.urls import path
 3 from app01 import views
 4 from django.conf.urls import url
 5 from django.conf import settings
 6 from django.conf.urls.static import static
 7 
 8 
 9 urlpatterns = [
10     path('admin/', admin.site.urls),
11     # url(r'^login.html$', views.login),
12     url(r'^login.html$', views.Login.as_view()),
13     url(r'^index.html$', views.index),
14     url(r'^class.html$', views.class_handler),
15     url(r'^student.html$', views.index),
16     url(r'^teacher.html$', views.index),
17 ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

3. 正确导入jquery等静态文件

<script type="text/javascript" src="/static/jquery-3.3.1.js"></script>

  

猜你喜欢

转载自www.cnblogs.com/yangziyao/p/9224256.html