Django html链接static文件

注:现在网页开发需要将HTML,CSS,JavaScript分离,所以特在此记录一下Django如何令HTML链接外部静态文件

1.创建项目,App

2.将App添加到settings.py

3.书写views.py urls.py

4.在App文件夹下创建templates和static文件夹

5.在templates下书写各个HTML,可以写base.html,home.html(entends ‘base.html’), 还有其他板块的html

6.在static文件夹下建立css,image,javascript文件夹,各自在文件夹下放对应文件

此时,文件结构应该为

XXX/
├── YYY
│     ├── __init__.py
│     ├── admin.py
│     ├── migrations
│     │       └── __init__.py
│     │
│     ├── models.py
│     ├── static # 应用 YYY 下的 static, 默认会找这个文件夹
│     │       └── javascript
│     │                └──a.js
│     │       └── css
│     │              └── c.css
│     │       └── image
│     │              └── b.png
│     ├── templates #文件省略
│     │   
│     ├── tests.py
│     │
│     └── views.py
│   
├── XXX
│     ├── __init__.py
│     ├── settings.py
│     ├── urls.py
│     └── wsgi.py
└── manage.py

注:由于static访问机制,当一个项目包含多个App时,App1的static文件可能被App2链接引用。所以可以在static,templates下再建一个与App同名的文件夹,再在该App同名文件夹下放HTML,CSS,JavaScript文件

7.在base.html的head中引入css,javascript,句式:

    {% load static %}   //{% load staticfiles %}也可以
    <link rel="shortcut icon" href="{% static 'image/b.png' %}" />
    <link rel="stylesheet" type="text/css" href="{% static 'css/c.css' %}" />
    <script src="{% static 'javascript/a.js' %}" type="text/javascript"></script>

8.假如.css文件引用了image文件夹中的图片,可以将文件地址设置为:

    background: url("../image/b.png");

9.假如一个项目中多个App都需要用到某个静态文件,则可以在 settings.py 中指定所有 app 共用的静态文件,比如 aa.js,bb.png 等

STATIC_URL = '/static/'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "common_static"),
)

在项目文件夹下,新创建common_static文件夹,将aa.js放在 common_static/javascript/ 下;bb.png放在 common_static/image/ 下,则就可以在 /static/javascript/aa.js , /static/image/bb.png 访问到相应的文件

最终文件结构大致为:

XXX/
├── YYY
│     ├── __init__.py
│     ├── admin.py
│     ├── migrations
│     │       └── __init__.py
│     │
│     ├── models.py
│     ├── static 
│     │       └── javascript
│     │                └──a.js
│     │       └── css
│     │              └── c.css
│     │       └── image
│     │              └── b.png
│     ├── templates #文件省略
│     │   
│     ├── tests.py
│     │
│     └── views.py
│ 
├── common_static # 已经添加到了 STATICFILES_DIRS 的文件夹
│      └── javascript
│      │       └── aa.js  
│      └── image
│              └── bb.png  
├── XXX
│     ├── __init__.py
│     ├── settings.py
│     ├── urls.py
│     └── wsgi.py
└── manage.py

猜你喜欢

转载自blog.csdn.net/liuyh73/article/details/78373979