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

前端之家收集整理的这篇文章主要介绍了django实战(五)--增加数据前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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,北京大学出版社(选择),我是个爱学习的人呀,哈哈哈

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

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

猜你在找的Django相关文章