urls.py
urlpatterns=[ path('curd/add/',views.curd_add,name='curdadd'), path('curd/saveadd/',views.curd_save_add,name='curdsaveadd'), ]
views.py
def curd_add(request): #我们这不对publisher表进行增加,只是增加book表,所以我们的publisher直接获取给前台用 publisher_obj=Publisher.objects.all() content={ 'publisher':publisher_obj, } return render(request,'curd/add.html',context=content) def curd_save_add(request): #判断是否是POST请求 if request.method == 'POST': title=request.POST.get('title') publisher=request.POST.get('publisher') introduce=request.POST.get('introduce') publisher_obj=Publisher.objects.get(name=publisher) #由于publisher表与book是关联关系,因此增加时publisher必须是对象 Book.objects.create(title=title,introduce=introduce,publisher=publisher_obj) return redirect('/curd/')
add.html
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.css"> <script src="/static/bootstrap/js/bootstrap.js"></script> <script type="text/javascript" src="http://libs.baidu.com/jquery/1.11.1/jquery.min.js"></script> <script src="/static/js/curd.js"></script> <title>Document</title> </head> <body> <div align="center" style=" 500px;position: absolute;top: 150px;left: 400px;"> <form method="post" class="form-horizontal" action="{% url 'person:curdsaveadd'%}"> <div class="form-group"> <label for="title" class="col-sm-2 control-label">title</label> <div class="col-sm-10"> <input type="text" class="form-control" name="title" id="title" > </div> </div> <div class="form-group"> <label for="publisher" class="col-sm-2 control-label">publisher</label> <div class="col-sm-10"> <select class="form-control" name="publisher"> {% for pub in publisher%} <option value="{{pub}}" >{{pub}}</option> {% endfor %} </select> </div> </div> <div class="form-group"> <label for="introduce" class="col-sm-2 control-label">introduce</label> <div class="col-sm-10"> <textarea type="text" name="introduce" class="form-control" id="introduce"></textarea> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-default">提交</button> </div> </div> </form> </div> </body> </html>
启动服务器:
点击添加按钮,浏览器地址变为http://127.0.0.1:8000/curd/add/
我们输入相应数据test,北京大学出版社(选择),我是个爱学习的人呀,哈哈哈
我们看到,数据已经插入进去了。
技术总结:就是关联表的插入需要进行对象插入。