先看效果:
路由部分代码:
from django.contrib import admin
from django.urls import path
from content.views import index
urlpatterns = [
path('admin/', admin.site.urls),
path('index/',index),
]
视图部分代码:
from django.shortcuts import render
from django.shortcuts import HttpResponse
from content.models import Content
def index(request):
if request.method == 'GET':
info = Content.objects.all()
cont = {'info': info}
return render(request,'content/index.html',cont)
else:
t = request.POST.get('tjtime')
n = request.POST.get('tjname')
txt = request.POST.get('tjtext')
msql = Content(u_time=t,u_name=n,u_content=txt)
msql.save()
# return HttpResponse('<h3>提交留言成功!</h3><br><hr><a href="http://139.198.16.166/index/">返回首页</a>')
info = Content.objects.all()
cont = {'info': info}
return render(request, 'content/index.html', cont)
模板部分代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>留言系统</title>
<style>
*{
margin: 0;
padding: 0;
}
.header{
background-color: #96b97d;
height: 50px;
}
.box{
width: 60%;
margin-left: 60px;
margin-top: 20px;
}
.content{
width: 100%;
}
th,td{
text-align: center;
height: 30px;
}
th{
background-color: #96b97d;
font-family: 楷体;
}
td{
background-color: #f6f6f6;
font-family: 新宋体;
color: red;
}
.header1{
float: left;
height: 50px;
color: black;
text-align: center;
line-height: 50px;
margin-left: 10px;
font-family: 楷体;
}
.vbox{
position: fixed;
top: 75px;
right: 60px;
width: 25%;
height: 70%;
background-color: #f6f6f6;
}
.head{
height: 30px;
text-align: center;
font-family: serif;
font-size: 10px;
background-color: #96b97d;
line-height: 30px;
}
.txt{
margin-left: 30px;
}
#i1{
margin-top: 20px;
height: 20px;
}
#i2{
margin-top: 20px;
height: 20px;
}
#i3{
margin-top: 20px;
height: 150px;
}
label{
font-family: 黑体;
}
#i4{
background-color: #96b97d;
margin-left: 30px;
border: none;
padding: 5px;
margin-top: 20px;
width: 100px;
}
</style>
</head>
<body>
<div class="header">
<div class="header1">
<h1>留言系统</h1>
</div>
</div>
<div class="box">
<table class="content">
<thead>
<tr>
<th>留言时间</th>
<th>留言姓名</th>
<th>留言内容</th>
</tr>
</thead>
<tbody>
{% for i in info %}
<tr>
<td width="200px">{{ i.u_time|date:"Y-m-d H:i:s"}}</td>
<td width="200px">{{ i.u_name }}</td>
<td>{{ i.u_content }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div class="vbox">
<form action="" method="post">
{% csrf_token %}
<div class="head">
<h1>留言板</h1>
</div>
<div class="txt">
<input type="datetime-local" name="tjtime" id="i2" placeholder="时间">
</div>
<div class="txt">
<input type="text" name="tjname" id="i1" placeholder="姓名">
</div>
<div class="txt">
<textarea name="tjtext" id="i3" cols="30" rows="10" placeholder="请输入... ..."></textarea>
</div>
<input type="submit" value="提交留言" id="i4">
</form>
</div>
</body>
</html>
数据库部分–模型:
from django.db import models
# Create your models here.
class Content(models.Model):
u_time = models.DateTimeField(auto_now=True)
u_name = models.CharField(max_length=20)
u_content = models.CharField(max_length=100)