templates文件夹下是模板文件
如winword.doc、powerpnt.ppt、excel.xls等模板就是包含有段落结构、字体样式和页面布局等元素的样式。它决定了文档的基本结构和设置的样式。
模板系统:
index.html:(在templates文件夹下建立)
<p>
谨定于{{ year }}年公历{{ month }}月{{ day }}日({{ week }})
农历{{ calendar }}为{{ groom }}、{{ bride }}举行婚礼敬备薄酒酌恭候{{ sir }}、{{ mrs }}夫妇光临{{ hotel }}大酒店, 地址:{{ address }} 敬约 恕邀
时间:下午{{ time }}时恭候
</p>
from django.shortcuts import render
def index(request):
data = {"year": "2018", "month": "12", "day": "29", "week": "星期一",
"calendar": "三月初一日", "groom": "美羊羊", "bride": "喜羊羊",
"sir": "灰太狼", "mrs": "红太狼", "hotel": "杨村",
"address": "杨村青草路杨村大酒店2楼", "time": "17:30"
}
return render(request, 'index.html', data)
由于settings.py中找不到templates文件路径,需要设置:
settings.py修改:
末尾处修改:
STATIC_URL = '/static/'
# TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'templates'),)
路径,大致第57行处修改:
'DIRS': [os.path.join(BASE_DIR, 'templates')],
例如:
views.py:
from django.shortcuts import render
def index(request):#data为二维字典
user_info={'name':'zs','age':20}
return render(request,'index.html',{'data':user_info})
class Person(object):#data为自定义对象
def __init__(self,name):
self.name=name
def dream(self):
return '{}的梦想是什么呢'.format(self.name)
def index1(request):
person=Person('张三')
return render(request,'index2.html',{'per':person})
def index2(request):#字典里套列表
lst = ['赵四', '小宝', '小沈阳', '刘能']
return render(request,'index2.html',{'f4':lst})
def index3(request):#字典里套列表,列表里套对象
person1 = Person('赵四')
person2 = Person('小宝')
person3 = Person('小沈阳')
person4 = Person('刘能')
lst = [person1, person2, person3, person4]
return render(request,'index2.html',{'f4':lst})
index2.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>
name:{{ data.name }}<br/>
age:{{ data.age }}
</p>
<hr/>
<p>
name:{{ per.name }}<br/>
age:{{ per.dream }}
</p>
<ul>
<li>{{ f4.0 }}</li>
<li>{{ f4.1 }}</li>
<li>{{ f4.2 }}</li>
<li>{{ f4.3 }}</li>
</ul>
<ul>
<li>{{ f4.0.name }}</li>
<li>{{ f4.1.name }}</li>
<li>{{ f4.2.name }}</li>
<li>{{ f4.3.name }}</li>
</ul>
</body>
</html>
from django.contrib import admin
from django.urls import path
from untitled2 import views
urlpatterns = [
path('admin/', admin.site.urls),
path('index/', views.index),
path('index1/', views.index1),
path('index2/', views.index2),
path('index3/', views.index3),
]