通过网页向DB内添加数据

结构如下:

mysite-
|
|--monitor
|    |
|    |--views
|       |--urls
|--mysite(默认创建)
|    |
|    |--settings
|       |--urls
|--templates
|    |
|    |--monitor
|          |--index.html

修改mysite.settings.py注释掉以下行

#‘django.middleware.csrf.CsrfViewMiddleware‘,

修改mysite.urls.py

urlpatterns = [ path(add/,views.add), #添加输入数据 path(del/,views.dell) #删除所有数据]

编辑monitor.views内容

from django.shortcuts import renderfrom django.http import HttpResponsefrom django.template import loaderfrom monitor.models import UserInfo as bdef add(request): if request.method == "POST": u=request.POST[Username] p=request.POST[Password] a=int(request.POST[Age]) b.objects.create(Username=u,Password=p,Age=a) k=b.objects.all() return render(request,monitor/index.html,{"lion":k})def dell(request): b.objects.all().delete() k = b.objects.all() return render(request, monitor/index.html, {"lion": k})

最后修改monitor.index


<!doctype html><html lang="zh-CN"><head> <title>django</title></head><body><form action="/add/" method="post"> <p><input name="Username" type="text"></p> <p><input name="Password" type="text"></p> <p><input name="Age" type="text"></p> <p><input value="提交" type="submit"></p></form><table border="1"> <thead> <tr> <th>用户名</th> <th>密码</th> <th>年龄</th> </tr> </thead> <tbody> {% for item in lion%} <tr> <td>{{ item.Username }}</td> <td>{{ item.Password }}</td> <td>{{ item.Age }}</td> </tr> {% endfor %} </tbody></table></body></html>

View Code

此时访问127.0.0.1:8000/{add,del}即可添加,删除数据内容

 

相关文章