一、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頁面所示: