• 技术文章 >后端开发 >Python教程

    django进阶学习记录

    高洛峰高洛峰2017-03-20 09:34:29原创681
    前言: 这篇博客对上篇博客django进阶作下补充。

    一、效果图

    django进阶学习记录

    php入门到就业线上直播课:进入学习

    前端界面较简单(丑),有两个功能:

    二、实现

    我们先来实现第一个功能,根据数据库数据在页面打印出书名。

    1. 添加url路由

        url(r'^book/', views.book),

    2. 在views.py定义book方法

    django默认使用GET方式,即获取数据;如果想创建/修改数据,比如待会要实现的第二个功能,就需要用POST方式。

    def book(request):
        books = models.Book.objects.all()  #找到所有的书
        publisher_list = models.Publisher.objects.all()
        author_list = models.Author.objects.all()
     
        print("---->:", request)
        return render(request, "app01/book.html", {"books":books,
                                                         "publishers":publisher_list,
                                                         "authors":author_list})


    3. 在templates/app01下创建book.html:

    books为数据库中所有书的对象集合,在html用个循环便可在前端页面显示书名。

    <h2>书列表:</h2>
        <ul>
            {% for book in books %}
                <li>{{ book.name }}</li>
            {% endfor %}
        </ul>

    接下来实现第二个功能,创建数据。

    先来看前端的html:

    <form method="post" action="/payment/book/"> {% csrf_token %}
            book name:<input type="text" name="name"/>
            <select name="publisher_id">
                {% for publisher in publishers %}
                    <option value="{{ publisher.id }}">{{ publisher.name }}</option>
                {% endfor %}
            </select>
            <select name="author_ids" multiple="multiple">
                {% for author in authors %}
                    <option value="{{ author.id }}">{{ author.first_name }}</option>
                {% endfor %}
            </select>
            <div>
                <input type="submit" value="创建新书"/>
            </div>
        </form>

    注意:

    再来看后台book方法

    def book(request):
        if request.method == "POST":  #若是创建书的数据
            print(request.POST)
            book_name = request.POST.get("name")
            publisher_id = request.POST.get("publisher_id")
            # 即使在前端页面选择多个作者只会返回一个值,只能取到最后一个作者的id
            #author_ids = request.POST.get("author_ids")
            author_ids = request.POST.getlist("author_ids") #getlist 可取出所有作者的id
    
            #生成一个书的对象
            new_book = models.Book(
                name = book_name,
                publisher_id = publisher_id,
                publish_date = "2017-3-18"
            )
            new_book.save()  #同步到数据库
    
            #new_book.authors.add(1,2) 添加作者
            new_book.authors.add(*author_ids) #author_ids为列表,需在前面加上*转化为id
    
            print("------->>:", book_name,publisher_id,author_ids)
    
        books = models.Book.objects.all()
        publisher_list = models.Publisher.objects.all()
        author_list = models.Author.objects.all()
    
        print("---->:", request)
        return render(request, "app01/book.html", {"books":books,
                                                         "publishers":publisher_list,
                                                         "authors":author_list})

    当我在前端界面输入书名: 新书A, 选中第二个出版社,选中第2和第3个作者,为了方便看,我在后台打印出来了:

    <QueryDict: {'name': ['新书A'], 'csrfmiddlewaretoken': ['V9OdHSJ10OFSq3r
    vI41tggns1W2VxwV'], 'publisher_id': ['2'], 'author_ids': ['2', '3']}>
    ------->>: 新书A 2 ['2', '3']
    ---->: <WSGIRequest: POST '/payment/book/'>
    [18/Mar/2017 14:06:23] "POST /payment/book/ HTTP/1.1" 200 1335

    根据打印结果知道author_ids是一个列表,当我为书添加作者时,用下面的代码:

    new_book.authors.add(*author_ids)

    为什么要在列表前加上*?不加上*是会曝错的! 加上*是为了将列表形式["2","3"]转化为作者id形式2,3。

    登陆admin后台查看刚刚创建的新书A:

    django进阶学习记录

    以上就是django进阶学习记录的详细内容,更多请关注php中文网其它相关文章!

    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。

    前端(VUE)零基础到就业课程:点击学习

    清晰的学习路线+老师随时辅导答疑

    自己动手写 PHP MVC 框架:点击学习

    快速了解MVC架构、了解框架底层运行原理

    专题推荐:django
    上一篇:python实用库学习PrettyTable的详细说明 下一篇:自己动手写 PHP MVC 框架(40节精讲/巨细/新人进阶必看)

    相关文章推荐

    • ❤️‍🔥共22门课程,总价3725元,会员免费学• ❤️‍🔥接口自动化测试不想写代码?• Python NumPy教程之数据类型对象• 使用Python处理KNN分类算法• Python标准库中的logging用法示例• python发腾讯微博代码分享• python自动化测试实例解析
    1/1

    PHP中文网