创建 Django 的过程可以参考上一篇文章 https://www.cnblogs.com/klvchen/p/10601536.html
在 templates 文件夹下创建一个 index.html 文件来提交和展示数据
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<fORM action="/userInfo" method="post">
<p>名字<input type="text" name="username"></p>
<p>性别<input type="text" name="sex"></p>
<p>邮箱<input type="text" name="email"></p>
<p><input type="submit" value="submit"></p>
</form>
<hr>
<h1>数据展示</h1>
<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>
在 views.py 文件中编写逻辑
from djanGo.shortcuts import render
# Create your views here.
user_list=[]
def userInfo(req):
if req.method=="POST":
username = req.POST.get("username", None)
sex = req.POST.get("sex", None)
email = req.POST.get("email", None)
user = {"username":username, "sex":sex, "email":email}
user_list.append(user)
return render(req, "index.html", {"user_list":user_list})
在 urls.py 文件中添加路径
from django.contrib import admin
from django.urls import path
from blog import views
urlpatterns = [
path('admin/', admin.site.urls),
path('userInfo', views.userInfo),
]
因为涉及到表单提交,暂时把检查跨域安全的配置注释,在 settings.py 文件中注释
#'django.middleware.csrf.CsrfViewMiddleware',
启动服务后,浏览器访问 Http://127.0.0.1:8888/userInfo