建立django學生信息錄入系統html
1,新建項目前端
2,編輯app目錄下 models.py python
class Stu(models.Model):git
name=models.CharField(max_lenth=32)數據庫
age=models.IntegerField()django
sex=models.CharField(max_lenth=32)app
3,執行數據庫遷移函數
python manage.py makemigrationsoop
python manage.py migratepost
4,編輯app目錄下views.py
先引進 HttpResponse,redirect
from django.shortcuts import render,HttpResponse,redirect
再引進 models
from app01 import models
定義 show 函數
def show(request):
obj=models.Stu.objects.all()
return render(request,"show.html",{"obj":obj})
5,templates 目錄下創建 show.html 進行編輯
建立table表單
<table border="1"> <tr> <th>序號</th> <th>ID </th> <th>姓名</th> <th>年齡</th> <th>性別</th> <th>編輯</th> </tr> {% for i in obj %} <tr> <td>{{ forloop.counter }}</td> <td>{{ i.id }}</td> <td>{{ i.name }}</td> <td>{{ i.age }}</td> <td>{{ i.sex }}</td> <td>編輯</td> </tr> {% endfor %} </table>
6,編輯urls.py
先引入 app01 目錄下 views
from app01 import views
再編輯路由
urlpatterns = [
path("show/",views.show),
]
7,此時已經能夠在前端頁面展現數據庫信息,下一步建立添加信息功能。
8,在show.html 頁面建立添加按鈕,實現跳轉到添加信息頁面
建立a標籤
<a href="/add/"><button>添加</botton></a>
9,在 templates 目錄建立 add.html,而且建立form表單
<form action="" method="post"> {% csrf_token %} 姓名:<input type="text" name="name"><br> {{ msg }} 年齡:<input type="text" name="age"><br> 性別:<input type="text" name="sex"><br> <input type="submit" value="提交"> </form>
而後繼續在views.py 建立add添加功能函數
def add(request):
if request.method=="GET":
return render(requst,"add.html")
msg=""
if request.method=="POST":
name=request.POST.get("name")
age=request.POST.get("age")
sex=request.POST.get("sex")
if name and age and sex:
if str(age).isdigit()==True:
if sex =="男" or sex=="女":
obj=models.Stu.objects.filter(name=name)
if obj:
return HttpResponse("名字已存在")
else:
models.Stu.objects.create(name=name,age=age,sex=sex)
else:
msg="性別只能是男或女"
else:
msg="年齡只能是數字"
else:
msg="數據不能爲空"
return render(request,"add.html",{"msg"=msg})
10,添加路由
path("add/",views.add)
11,運行項目