当前位置 : 主页 > 编程语言 > python >

Django从理论到实战(part24)--在模板中访问静态文件

来源:互联网 收集:自由互联 发布时间:2022-06-15
学习笔记,仅供参考 参考自:Django打造大型企业官网–Huang Y; 本系列Blog以应用为主,理论基础部分我在后端专栏的Django系列博客已经写过了,如果有些需要补充的知识点,我会在这个

学习笔记,仅供参考

参考自:Django打造大型企业官网–Huang Y;

本系列Blog以应用为主,理论基础部分我在后端专栏的Django系列博客已经写过了,如果有些需要补充的知识点,我会在这个系列中,尽量详细的记录一下。



在模板中访问静态文件



  • 进入虚拟环境
workon mymkvir



  • 创建新项目
cd F:\MyStudio\PythonStudio\goatbishop.project01\Django
django-admin startproject newwebsite3



  • 配置静态文件路径

首先,我们在项目下创建static文件夹,并在里面存放TX.jpg文件,再进入settings.py

进行配置,在文件中添加STATICFILES_DIRS列表:

STATICFILES_DIRS = [
os.path.join(BASE_DIR,"static")
]

当我们进行以上配置之后,​​DTL​​就会在这个列表的路径中查找静态文件了。



  • 创建模板并导入静态文件

创建templates文件夹,并创建模板文件index.html:

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="{% static 'pink.css' %}">
</head>
<body>
<img src="{% static 'TX.jpg' %}">
</body>
</html>

在模版中,我们需要使用​​load​​​标签加载​​static​​标签。

在templates文件夹中,创建pink.css文件:

body {
background-color: pink;
}



  • 设置路由并创建视图函数

在urls.py文件中,创建路由:

from django.contrib import admin
from django.urls import path
from . import views

urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index),
]

在views.py文件中,创建视图函数:

from django.shortcuts import render


def index(request):
return render(request, "index.html")



  • 发起请求

向http://127.0.0.1:8000/发起请求:

Django从理论到实战(part24)--在模板中访问静态文件_html

上一篇:括号生成 (Python)
下一篇:没有了
网友评论