任务:下载素材,如下图所示:
将网页放到Django项目中运行,将下图红框中的文字和图片作为后台的数据,传递到页面进行显示。
1、将素材放入Django项目中
(1)新建应用exercise01用来完成网页的显示。
python manage.py startapp exercise01
将应用放到apps文件夹中,并将素材放至对应的位置。
2、配置路由
主目录路由
path("exercise01/",include(("apps.exercise01.urls",'exercise01'),namespace='exercise01')),
子路由:
from django.urls import path
from . import views
urlpatterns = [
path('',views.index,name='index'),
]
3、定义视图
def index(request):
return render(request,‘exercise01/index.html’)
4、查看效果
5、修改模板v1
{% load static %}
修改页面中CSS和图片的引用
<link rel="stylesheet" href="/static/css/public.css">
<link rel="stylesheet" href="/static/css/main.css">
<img src="/static/img/content-two-pic.jpg">
刷新看效果,页面正常显示。
6、修改视图
将数据传递到页面。
def index(request):
#return render(request,'exercise01/index.html')
context = {}
# 1、网页主题
topic = {}
topic['cn'] = '房屋服务中心'
topic['en'] = 'HOUSING SERVICE CENTER'
# 2、关于部分
about = {}
about['pic'] = 'wetu1.jpg'
about['txt1'] = '028=38383i38'
about['txt2'] = '028=38383i38'
# 3、管家服务
manage = {}
manage['cn'] = "装修管家服务"
manage['en'] = 'DECORATION HOUSEKEEPER SERVICE'
manage['pic'] = [
'content-two-pic.jpg',
'content-two-two.jpg',
'content-two-three.jpg',
'content-two-four.jpg',
'ai.jpg',
]
manage['title'] = '量房'
# 4、房屋居住环境
live = {}
live['cn'] = '房屋居住环境'
live['en'] = 'HOUSING AND LIVING ENVIRONMENT'
live['pic'] = [
'ike.jpg',
'lh.jpg',
'om.jpg',
'pic.jpg',
'931.jpg',
]
live['title'] = '居住'
# 5、将所有数据存储到字典中
context['topic'] = topic
context['about'] = about
context['manage'] = manage
context['live'] = live
return render(request, "index.html", context)
7、修改模板v2
在页面,通过键来访问数据。访问数据如下:
<div class="comm-title">
<h1>{{ topic.cn }}</h1>
<em>{{ topic.en }}</em>
</div>
<!-- 关于我们 -->
<div class="about-box">
<img class="about-img" src="/static/img/{{ about.pic }}">
<div class="about-text">
{{ about.txt1 }}<br> {{ about.txt2 }}<br>{{ about.pic }}
</div>
</div>
<li>
<a href="">
<img src="/static/img/{{ manage.pic.0 }}">
<div class="layer">
<h2>{{ manage.title }}</h2>
</div>
</a>
</li>
查看效果,正常。
8、修改模板v3
将图片的img路径写入到配置文件中。
修改图片的引用如下:
将
<img class="about-img" src="/static/img/{{ about.pic }}">
修改成如下:
<img class="about-img" src="/static/{{ about.pic }}">
以此类推。
查看页面效果,正常。
9、使用static标签完善模板(index.html)
<link rel="stylesheet" href="{% static 'css/public.css' %}">
<link rel="stylesheet" href="{% static 'css/main.css' %}">
将
<img class="about-img" src="/static/{{ about.pic }}">
修改成如下:
<img class="about-img" src="{% static about.pic %}">
以此类推进行修改。
页面显示正常。