[Django基础] django解决静态文件依赖问题以及前端引入方式

一、静态文件依赖

学习django的时候发现静态文件(css,js等)不能只在html中引入,还要在项目的settings中设置,否则会报以下错误

[11/Sep/2018 03:18:15] "GET /static/js/index.js HTTP/1.1" 404 1646
[11/Sep/2018 03:18:15] "GET /static/js/lib/vue/dist/vue.js HTTP/1.1" 404 1679
[11/Sep/2018 03:18:15] "GET /static/js/lib/jquery/dist/jquery.js HTTP/1.1" 404 1697
[11/Sep/2018 03:18:15] "GET /static/css/bootstrap/dist/js/bootstrap.js HTTP/1.1" 404 1715
[11/Sep/2018 03:18:15] "GET /static/css/bootstrap/dist/js/bootstrap.js HTTP/1.1" 404 1715
[11/Sep/2018 03:18:15] "GET /static/js/lib/vue/dist/vue.js HTTP/1.1" 404 1679
[11/Sep/2018 03:18:15] "GET /static/js/index.js HTTP/1.1" 404 1646

具体引入方法如下(静态文件均存放在static下):

1.INSTALLED_APPS

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]

2.STATIC_URL

STATIC_URL = '/static/'

3.STATICFILES_DIRS

STATICFILES_DIRS = [(os.path.join(BASE_DIR,'static'))] #这里必须是list或者tuple格式

引入后重新加载:

[11/Sep/2018 03:22:11] "GET / HTTP/1.1" 200 522
[11/Sep/2018 03:22:11] "GET /static/js/lib/jquery/dist/jquery.js HTTP/1.1" 200 271751
[11/Sep/2018 03:22:11] "GET /static/js/index.js HTTP/1.1" 200 1966
[11/Sep/2018 03:22:11] "GET /static/css/bootstrap/dist/js/bootstrap.js HTTP/1.1" 200 123765
[11/Sep/2018 03:22:11] "GET /static/js/lib/vue/dist/vue.js HTTP/1.1" 200 289303

二、前端引入方式有二:

1.{%static%}方式   

在页面的较上处写:
{% load staticfiles %}

在 link script 等src 写 :
{%static 'xxx.css'%} 
{%static 'xxx.js'%}

2./static/..方式

在 link script 等src 写 :
/static/xxx.cs

两者可混用,但不推荐

DONE。

上一篇:不用synchronized块的话如何实现一个原子的i++?


下一篇:IOS——触摸事件 视图检测和事件传递