加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

django实战(五)--增加数据

发布时间:2020-12-15 17:08:09 所属栏目:大数据 来源:网络整理
导读:urls.py urlpatterns= [ path( ' curd/add/ ' ,views.curd_add,name= curdadd ' ),path( curd/saveadd/ curdsaveadd views.py def curd_add(request): # 我们这不对publisher表进行增加,只是增加book表,所以我们的publisher直接获取给前台用 publisher_obj

urls.py

urlpatterns=[
    path('curd/add/',views.curd_add,name=curdadd'),path(curd/saveadd/curdsaveadd
def curd_add(request):
    #我们这不对publisher表进行增加,只是增加book表,所以我们的publisher直接获取给前台用
    publisher_obj=Publisher.objects.all()
    content={
        publisher:publisher_obj,}
    return render(request,curd/add.htmlcontent)

 curd_save_add(request):
    判断是否是POST请求
    if request.method == POST:
        title=request.POST.get(title)
        publisher=request.POST.get()
        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=width: 500px;position: absolute;top: 150px;left: 400px;">
    <form method=post" class=form-horizontal" action={% url 'person:curdsaveadd'%}">
        <div form-group">
            <label for=col-sm-2 control-label">title</label>
            <div col-sm-10">
                <input type=textform-control" name=" id=" >
            </div>
        </div>
        <div ">publisher</label>
            <div ">
                <select ">
                    {% for pub in publisher%}
                    <option  value={{pub}}" >{{pub}}</option>
                    {% endfor %}
                </select>
            </div>
        </div>
                <div ">introduce</label>
            <div ">
                <textarea type="></textarea>
            </div>
        </div>
        <div ">
            <div col-sm-offset-2 col-sm-10">
                <button type=submitbtn btn-default">提交</button>
            </div>
        </div>
    </form>
</div>
</body>
</html>

启动服务器:

?

?点击添加按钮,浏览器地址变为http://127.0.0.1:8000/curd/add/

?

?我们输入相应数据test,北京大学出版社(选择),我是个爱学习的人呀,哈哈哈

我们看到,数据已经插入进去了。

技术总结:就是关联表的插入需要进行对象插入。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读