一、DTL讲解:
1、DTL模板是一种带有特殊语法的html文件,这个HTML文件可以被Django编译,可以传递参数进去,实现数据动态化。在编译完成后,生成一个普通的HTML文件,然后发送给客户端。
2、在Django里通常在views.py文件中会定义视图函数,同时需要导入对应的库,导入库的命令通常是from django.shortcuts import render
from django.http import HttpResponse
其中上面一个render,中文名就是渲染的意思,也就是在views.py文件里定义的方法,会通过return render(request,'index.html',context=context)这样的方式将index.html文件进行渲染。index.html里会调用视图文件views.py里定义的变量,定义的方法和定义的属性。
二、示例讲解:
下面代码是对DTL的for,with等的讲解。
1、首先要创建项目和创建App,进入文件目录“E:ITPythonPYTHON试验”里,在地址栏输入cmd,进入cmd命令提示符环境下依次输入以下命令:
django-admin startproject demo08
cd demo08
python manage.py startapp books
相当于创建了一个demo08项目,在项目下创建了一个books的app,代码图示例如下:
2、进入pycharm,打开E:ITPYthonPYTHONdemo08这个文件夹。
①先设置项目目录下E:ITPYthonPYTHON试验demo08demo08settings.py的代码,代码设置如下:
"""
Django settings for demo08 project.
Generated by 'django-admin startproject' using Django 2.2.1.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '@f%my2rhwsou3p9%8xr1^r)#7j1d=c)!6(%8yk$7rehy-rh%=^'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'books', #需将app名称存入
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'demo08.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'templates')], #设置静态文件存放目录
'APP_DIRS': True, #为True代表在设置的上面一行DIRS里如果找不到静态文件的话,会自动去app目录下寻找静态文件
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'demo08.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'zh-Hans' #设置中文语言
TIME_ZONE = 'Asia/Shanghai' #设置上海时区
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (css, JAVAScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
真正需要设置的只有4行,分别是
①在INSTALLED_APPS里添加app文件名,即'books',
②在TEMPLATES里设置DIRS的值,设置为[os.path.join(BASE_DIR,'templates')],这项时用来设置静态文件存放目录
③LANGUAGE_CODE = 'zh-Hans' #设置中文语言
④TIME_ZONE = 'Asia/Shanghai' #设置上海时区
3、在app目录创建E:ITPYthonPYTHON试验demo08books\urls.py文件,即创建app下面的路由文件,在路由文件里的代码如下:
from django.urls import path
from . import views
urlpatterns=[
path('',views.index),
path('book0/',views.book0,name='book0'),
path('book1/',views.book1,name='book1'),
path('book2/',views.book2,name='book2'),
path('book3/',views.book3,name='book3'),
path('book4/',views.book4,name='book4'),
]
4、在app目录E:ITPYthonPYTHON试验demo08booksviews.py下编辑视图文件,即编辑views.py文件,代码如下:
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
context={"books":[
"python编程从入门到实战",
"python面向对象编程指南",
"python网络爬虫权威指南",
"python机器学习经典实例",
"零起点TensorFlow快速入门",
],
"books2":[
"西游记",
"水浒传",
"红楼梦",
"三国演义"
],
"persons":
{
"嬴政":"秦朝的开国皇帝",
"刘秀":"位面之子,东汉开国皇帝,秀才造反,不鸣则已一鸣惊人",
"李世民":"唐朝杰出的皇帝,人称天可汗",
"毛泽东": "新中国国家主席",
},
"movies":[
{
"name":"泰囧",
"box_office":"12.77亿",
"Director":"徐峥"
},
{
"name": "攀登者",
"box_Office": "22.47亿",
"Director": "吴京"
},
{
"name": "中国机长",
"box_Office": "20.56亿",
"Director": "刘伟强"
}],
"comments":["电影真好","很有励志意义"],
"goods":["apple","banana","orange"],
"students":["张三","李思","王五"]
}
return render(request,"index.html",context=context)
def book0(request):
return HttpResponse("从入门到实践是一本针对所有层次的Python读者而作的Python入门书。")
def book1(request):
return HttpResponse("Python面向对象编程指南.[美]Steven F.Lott(带详细书签),分成两个压缩包。本书由树莓派基金会资深软件开发工程师亲笔撰写,是学习在树莓派上编程的必备手册。即使你没有任何编程经验,也可以畅游树莓派的世界。本书覆盖了初学编程者和第一次做Python开发所需的基础知识,书中首先对Python编程做了基本介绍,并给出了通用的Python代码,然后逐步介绍了。")
def book2(request):
return HttpResponse("本书采用简洁强大的Python语言,全面介绍网页抓取技术,解答诸多常见问题,是掌握从数据爬取到数据清洗全流程的系统实践指南")
def book3(request):
return HttpResponse("Python机器学习经典实例首先通过实用的案例介绍机器学习的基础知识,然后介绍一些稍微复杂的机器学习算法,例如支持向量机、极端随机森林、隐马尔可夫模型、条件随机场、深度神经网络,等等")
def book4(request):
return HttpResponse("TensorFlow是近年来影响最大的神经网络和深度学习平台,《零起点TensorFlow快速入门》以生动活泼的语言,从入门者的角度,对TensorFlow进行介绍,书中包含大量简单风趣的实际案例,如孤独的神经元、梵高画风等,让广大初学者快速掌握神经网络的基本编程,为进一步学习人工智能奠定扎实的基础。")
5、编辑项目路由下的url文件,文件路径是E:ITPYthonPYTHON试验demo08demo08\urls.py,编写代码如下:
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('books/',include('books.urls')),
]
6、在静态文件目录下创建静态HTML文件,静态HTML文件目录是E:ITPYthonPYTHON试验demo08templatesindex.html,在其中编辑代码,代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>书籍</title>
<embed src="https://www.kugou.com/song/#hash=04E4C1D0AFB9DEEF3B0834AA1F71B654&album_id=26382011" width:100% margin-left:auto>
<style>
.nav1{
overflow:hidden;
}
.nav1 li{
float:left;
list-style:none;
margin:0 20px;
}
.nav2 li{
float:left;
list-style:none;
margin:0 20px;
}
</style>
</head>
<body style="background:skyblue;text-align:left;width:90%;margin-left:auto;margin-right:auto;">
<div id="book" style="width:100%;heigth:40%;border:1px solid blue;margin-left:auto;">
<h4><strong> python书籍</strong></h4>
<以下是通过for book in books遍历方式获取的书籍数据>
<ul class="nav1">
{%for book in books%}
<li>{{book}}</li>
{%endfor%}
</ul>
<以下是通过books.0这样的方式获取的书籍数据>
<ul class="nav2">
<li><a href="{%url 'book0'%}">{{books.0}}</a></li>
<li><a href="{%url 'book1'%}">{{books.1}}</a>></li>
<li><a href="{%url 'book2'%}">{{books.2}}</a>></li>
<li><a href="{%url 'book3'%}">{{books.3}}</a></li>
<li><a href="{% url 'book4'%}">{{books.4}}</a></li>
</ul>
<br>
<h4> 四大名著</h4>
<ul>
{% for book2 in books2 %}
<li>{{ book2 }}</li>
{% endfor %}
</ul>
</div>
<div id="human" style="width:100%;heigth:30%;border:1px solid blue">
<h4> 中国名人</h4>
<ul>
{% for person,personvalue in persons.items %}
<li>{{person}} : {{personvalue}}</li>
{% endfor %}
</ul>
</div>
<div id="movies" style="width:100%;heigth:100%;border:1px solid blue">
<h4> 电影</h4>
<table>
<thead>
<tr>
<th>序号</th>
<th>电影名称</th>
<th>票房</th>
<th>导演</th>
</tr>
</thead>
<tbody>
<tr>
{% for movie in movies %}
{% if forloop.first %}
<tr style="background:red">
{% elif forloop.last%}
<tr style="background:green">
{%else%}
<tr>
{%endif%}
<td>{{forloop.counter}}</td>
<td>{{ movie.name }}</td>
<td> {{ movie.box_Office }}</td>
<td>{{ movie.Director }}</td>
{% endfor %}
</tr>
</tbody>
</table>
</div>
<div id="others" style="border:1px solid blue">
<h4> 评论信息</h4>
<ul>
{% for comment in comments%}
<li>{{comment}}</li>
{%empty%}
<li>没有任何评论</li>
{%endfor%}
</ul>
<h4> 水果商品</h4>
{% with gd=goods.0%}
<p> {{gd}}</p>
{%endwith%}
<h4> 学生姓名</h4>
{% with students.0 as st1%}
<p> {{st1}}</p>
{%endwith%}
</div>
</body>
</html>
7、在pycharm下方的Terminal终端中输入命令:
python manage.py runserver
如下图所示:
8、代码运行结果如下面的HTML页面所示: