![13423234-c8e484b60d8cd3cc.png](https://upload-images.jianshu.io/upload_images/13423234-c8e484b60d8cd3cc.png)
在Django项目中,对于 js、css、images 等静态文件资源,需要一个公共的存放路径,不然每个应用都新建一个 static 文件夹的话,其实很不方便。
那么该怎么配置呢?
配置 settings.py 的静态文件路径
在 STATIC_URL = '/static/'
下面添加代码
![13423234-1e35d24e381a466f.png](https://upload-images.jianshu.io/upload_images/13423234-1e35d24e381a466f.png)
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
在项目根路径下新建 static 文件夹,并添加以下子文件夹和文件
文件结构如下:
![13423234-c43f1019f07b6be9.png](https://upload-images.jianshu.io/upload_images/13423234-c43f1019f07b6be9.png)
好了,这样就配置好了项目下的公共静态文件了。下面来继续配置公共模板路径。
配置 settings.py 的模板文件路径
设置TEMPLATES的DIRS值,如下:
'DIRS': [os.path.join(BASE_DIR, 'templates')],
![13423234-c6c6166c07910ccc.png](https://upload-images.jianshu.io/upload_images/13423234-c6c6166c07910ccc.png)
在项目路径下,创建 templates 文件夹,以及继续创建应用名称的文件夹
文件结构如下:
![13423234-6a847dc415acd850.png](https://upload-images.jianshu.io/upload_images/13423234-6a847dc415acd850.png)
那么配置了这样的模板路径之后,应用assetinfo该怎么调用呢?
查看应用的调用模板方式
![13423234-a3d9d24fe9543c33.png](https://upload-images.jianshu.io/upload_images/13423234-a3d9d24fe9543c33.png)
因为定义好了 templates 的路径,所以只需要写上 templates 下的相对路径即可。
下面再放入另一个前端代码,用来测试调用静态文件的。
放入另一套前端代码
![13423234-c121d6a05bf629b0.png](https://upload-images.jianshu.io/upload_images/13423234-c121d6a05bf629b0.png)
可以知道刚才配置好了静态文件的存放路径,那么相应的html代码中的静态文件路径也是需要修改的。
在所有静态文件的前面增加 /static/
路径即可,如下:
![13423234-faaa0cb8c36a673c.png](https://upload-images.jianshu.io/upload_images/13423234-faaa0cb8c36a673c.png)
编写一个显示该页面的视图
![13423234-775561490dbcea8a.png](https://upload-images.jianshu.io/upload_images/13423234-775561490dbcea8a.png)
然后配置url路径,下面使用浏览器验证一下看看,如下:
![13423234-111b2002c11b063e.png](https://upload-images.jianshu.io/upload_images/13423234-111b2002c11b063e.png)
可以看到页面已经成功展示出来了。
查看页面源码,如下:
![13423234-0a8720918525b54c.png](https://upload-images.jianshu.io/upload_images/13423234-0a8720918525b54c.png)
![13423234-d6245d0b99f41c57.png](https://upload-images.jianshu.io/upload_images/13423234-d6245d0b99f41c57.png)
可以看到静态文件是可以正常访问的。
![13423234-0e3934319aa622f6.png](https://upload-images.jianshu.io/upload_images/13423234-0e3934319aa622f6.png)
转载于:https://www.jianshu.com/p/e8c03c01dc6e