# Static files (CSS, JavaScript, Images)
STATIC_URL = '/static/'
{# static并不是DTL模板中内置的标签,因此要想使用的的话,就先要进行加载load进来 #}
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href=" {% static 'css/index.css' %} ">
</head>
<body>
# 可以采用第一种方式进行获取,但是此时获取图片的路径如果发生了变化,就要多处修改,比较麻烦,
{#<img src="/static/logo.jpg" alt="">#}
# 所以推荐使用第二种,使用static标签进行动态获取静态文件
<img src="{% static 'front/logo.jpg' %}" alt="">
</body>
</html>
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'static')
]
<link rel="stylesheet" href=" {% static 'css/index.css' %} ">
'builtins':[
'django.templatetags.static'
],
from django.urls import path
from front import views
from book import views as book_views
# 将静态文件的url与静态文件的路径进行拼接
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', views.index, name = 'index'),
path('book/', book_views.book, name = 'book'),
] + static(settings.STATIC_URL,document_root = settings.STATICFILES_DIRS[0])
# 进行拼接的时候,static(url前缀(STATIC_URL),document_root(静态文件路径))
此时ctrl+shift+r刷新网页,同样可以加载静态文件(jpg图片、css文件):
原文:https://www.cnblogs.com/guyan-2020/p/12206336.html