創(chuàng)建模版
首先在項目目錄的 templates
文件夾中創(chuàng)建index.html
噪舀。
這里就是正常的HTML代碼魁淳,需要什么就寫什么樣式的就可以。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form action="/index/" method="POST">
<!--aciton 的地址与倡,就是在urls中配置的地址界逛。-->
<lable>姓名</lable><input type="text" name="username">
<lable>性別</lable><input type="text" name="sex">
<lable>郵箱</lable><input type="text" name="email">
<input type="submit" value="提交">
</form>
<table border="1px">
<tr>
<td>姓名</td>
<td>性別</td>
<td>郵箱</td>
</tr>
</table>
</body>
</html>
views 的編寫
編寫過程中主要注意以下幾點:
- 因為前端的 method 提交的是
POST
- Python 中就需要對POST獲取,
request.POST.get()
- 獲取什么見表單中控件的
name
- 將結(jié)果加入字典纺座,以便模版語言使用
- 記住息拜,因為創(chuàng)建了列表
user_list
6.最后的render
需要將'user_list'封裝{"user_list":user_list}
,一定要注意格式净响,用{}
包起來少欺。
from django.shortcuts import render
user_list=[]
def index(request):
username = request.POST.get("username",None)
sex = request.POST.get("sex",None)
email = request.POST.get("email",None)
user ={"username":username,"sex":sex,"email":email}
user_list.append(user)
return render(request,"index.html",{"user_list":user_list})
模版語言
再要展示的地方插入模版語言。
模版語言:個人理解(可能理解不對)就是 通過 vender
來實現(xiàn)對html的操作馋贤。
{% for i in user_list %}
<tr>
<td>{{ i.username }}</td>
<td>{{ i.sex }}</td>
<td>{{ i.email }}</td>
</tr>
{% endfor %}
完整代碼
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form action="/index/" method="POST">
<!--aciton 的地址赞别,就是在urls中配置的地址。-->
<lable>姓名</lable><input type="text" name="username">
<lable>性別</lable><input type="text" name="sex">
<lable>郵箱</lable><input type="text" name="email">
<input type="submit" value="提交">
</form>
<table border="1px">
<tr>
<td>姓名</td>
<td>性別</td>
<td>郵箱</td>
</tr>
{% for i in user_list %}
<tr>
<td>{{ i.username }}</td>
<td>{{ i.sex }}</td>
<td>{{ i.email }}</td>
</tr>
{% endfor %}
</table>
</body>
</html>