数据库模型demon
from django.db import models # Create your models here. class Test(models.Model): name=models.CharField(max_length=20)
settings内的tempales路径修改:
'DIRS': [BASE_DIR+"/templates",],
前端代码 取名为save_data.html
<!DOCTYPE html> <!DOCTYPE html> <html> <head> <title>数据库操作</title> </head> <body> <form action="/save_data" method="post"> {% csrf_token %} <ul> <li> 请输入名字<input type="text" name="add_data"> <button type="submit" name="add">添加数据</button> </li> <li> 请输入 ID<input type="text" name="update_data"> <button type="submit" name="update">更新数据</button> </li> <li> 请输入 ID<input type="text" name="delete_data"> <button type="submit" name="delete">删除数据</button> </li> <li> 请输入 ID<input type="text" name="select_data"> <button type="submit" name="select">查询数据</button> </li> </ul> </form> <p>{{ result }}</p> </body> </html>
调用前端的代码,取名为save.py
from django.shortcuts import render from TestModel.models import Test from django.views.decorators import csrf def save_data(request): data={} if request.POST: if 'add' in request.POST: test1 = Test(name=request.POST['add_data']) test1.save() data['result']='数据添加成功' if 'update' in request.POST: ID=int(request.POST['update_data']) test1=Test.objects.get(id=ID) test1.name='change' test1.save() data['result']='数据修改成功' if 'delete' in request.POST: ID=int(request.POST['delete_data']) test1=Test.objects.get(id=ID) test1.delete() data['result']='删除数据成功' if 'select' in request.POST: ID=int(request.POST['select_data']) test1=Test.objects.get(id=ID) data['result']=test1.name return render(request,'save_data.html',data)
最后修改urls
from django.conf.urls import url from . import save urlpatterns = [ url(r'^save_data$',save.save_data) ]
python manage.py runserver后访问http://127.0.0.1:8000/save_data
访问后网页显示
添加数据后