管理静态文件(比如图片、JavaScript、CSS)
网站通常需要提供类似图片,JavaScript 或 CSS 的额外文件服务。在 Django 中,我们将这些文件称为“静态文件”。Django 提供了 django.contrib.staticfiles 帮你管理它们。 配置静态文件¶
1、确保 INSTALLED_APPS 包含了 django.contrib.staticfiles。
2、在配置文件中,定义 STATIC_URL,例子:
STATIC_URL = '/static/'
3、在模板中,用 static 模板标签基于配置 STATICFILES_STORAGE 位给定的相对路径构建 URL。
{% load static %}
<img src="{% static "my_app/example.jpg" %}" alt="My image">
4、将你的静态文件保存至程序中名为 static 的目录中。例如 my_app/static/my_app/example.jpg。
你的工程可能包含未与任何应用绑定的静态资源。除了在 apps 中使用 static/ 目录,你可以在配置文件中定义一个目录列表 (STATICFILES_DIRS) ,Django 会从中寻找静态文件。例子:
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
'/var/www/static/',
]
参考官方文档: https://docs.djangoproject.com/zh-hans/3.0/howto/static-files/
5、DEBUG 开发模式关闭后
# 对外提供WEB访问时的URL地址
STATIC_URL = '/static/'
# 开发阶段放置项目自己的静态文件,不能包含STATIC_ROOT路径
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'staticfiles'),
)
# 执行collectstatic命令后会将项目中的静态文件(包括STATICFILES_DIRS、自带admin的静态文件)收集到该目录下面来(所以不应该在该目录下面放置自己的一些静态文件,因为会覆盖掉)
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
(env381) [root@10-11-12-120 ylcost]# python manage.py collectstatic
You have requested to collect static files at the destination
location as specified in your settings:
/fjyl/Website/www.exaple.com/ylcost/static
This will overwrite existing files!
Are you sure you want to do this?
Type 'yes' to continue, or 'no' to cancel: yes
Found another file with the destination path 'admin/css/autocomplete.css'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path.
Django继续使用静态资源的办法
Django在非debug模式下,不处理静态资源文件,原因可能是性能,使用CDN比较好,但是小应用就不用了,解决办法:
python manage.py runserver 0:8888 --insecure
https://github.com/evansd/whitenoise
https://github.com/heroku-python/dj-static