• S20_DAY16--作业v1.0


    app01/models.py

    from django.db import models
    
    # Create your models here.
    
    
    class Book(models.Model):
        title=models.CharField(max_length=32)
        price=models.DecimalField(max_digits=6,decimal_places=2)
        create_time=models.DateField()
        memo=models.CharField(max_length=32,default="")
    
        # book_obj.publish: 与这本书籍关联的出版社对象
        publish=models.ForeignKey(to="Publish",default=1)
        # book_obj.author.all():  与这本书关联的作者对象集合,Queryset []
        authors=models.ManyToManyField("Author") # 自动创建第三张表
    
        def __str__(self):
            return self.title
    
    class Publish(models.Model):
        name=models.CharField(max_length=32)
        email=models.CharField(max_length=32)
    
    class Author(models.Model):
        name=models.CharField(max_length=32)
    
        def __str__(self):return self.name
    
    
    
    # class Author2Book(models.Model):
    #     book=models.ForeignKey("Book")
    #     author=models.ForeignKey("Author")

    [projectname]/urls.py

    """cms_s20 URL Configuration
    
    The `urlpatterns` list routes URLs to views. For more information please see:
        https://docs.djangoproject.com/en/1.11/topics/http/urls/
    Examples:
    Function views
        1. Add an import:  from my_app import views
        2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
    Class-based views
        1. Add an import:  from other_app.views import Home
        2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
    Including another URLconf
        1. Import the include() function: from django.conf.urls import url, include
        2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
    """
    from django.conf.urls import url,include
    from django.contrib import admin
    from django.shortcuts import HttpResponse
    
    from app01.views import *
    
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        # url(r'^timer/$', timer), # timer(request)
        # url(r'^books_achrive/(d+)/$', book_detail), # book_detail(request,3)
        # #url(r'^books_achrive/(d+)/(d+)/$', books_achrive), # books_achrive(request,2012,12)
        # url(r'^books_achrive/(?P<year>d+)/(?P<month>d+)/$', books_achrive2), # books_achrive(request,year=2012,month=12)
        url(r'^login/', login,name="xxx"),
        url(r'^app01/', include('app01.urls'),),
        url(r'^template/', temp_func,),
        url(r'^add/', add,),
        url(r'^query/', query,),
        url(r'^books/', books,),
        url(r'^$', books,),
        url(r'^addbook/', addbook,name='add_book'),
        url(r'^edit/(d+)', editbook,name='edit_book'),
        url(r'^del/(d+)', delbook,name='del_book'),
    
    ]
    
    
    #  url的路径:/books/3与正则匹配 /book/d+
    
    # import re
    #
    # re.findall("^books_achrive/(d+)/$","books_achrive/2012/12/")

    app01/views.py

    from django.shortcuts import render,HttpResponse,redirect
    
    # Create your views here.
    def timer(request):
    
        import time
        ctime=time.time()
        #return HttpResponse(ctime)
        return render(request,"timer.html",{"ctime":ctime})
    
    def book_detail(reqeust,id):
    
        return HttpResponse(id)
    
    def books_achrive(request,year,month):
    
        return HttpResponse(year+":"+month)
    
    def books_achrive2(request,month,year):
    
        return HttpResponse(year+":"+month)
    
    def login(request):
    
        if request.method=="GET":
            print(request.GET)
            print(request.POST)
            print(request.method)
            print(request.path)
            print(request.path_info)
            print(request.body)
            return render(request, "login.html")
    
        else:
    
            print(request.GET)
            print(request.POST)
            print(request.method)
            print(request.path)
            print(request.path_info)
            print(request.body)
    
            user=request.POST.get("user")
            pwd=request.POST.get("pwd")
            if 1:
                return redirect("/app01/timer/")
    
    
    def temp_func(request):
    
        l=[11,222,333]
        dic={"name":"yuan","age":23}
    
        class Person(object):
            def __init__(self,name,age):
                self.name=name
                self.age=age
            def learning(self):
                 return "learning"
        alex=Person("alex",45)
        egon=Person("egon",36)
        person_list=[alex,egon]
    
        import datetime
        now=datetime.datetime.now()
        print(now)
    
        file_size=234212123123
    
        content="hello yuan world egon alex"
        s="<a href='http://www.baidu.com'>hello</a>"
        #return render(request,"temp.html",{"l":l,"dic":dic})
        return render(request,"temp.html",locals())
    
    
    from .models import *
    def add(request):
        # obj=Book.objects.create(title="python",price=123,create_time="2012-12-12")
        # print(obj.title)
    
        obj=Book(title="php",price=123,create_time="2012-12-12")
        obj.save()
        return HttpResponse("123")
    
    
    def query(request):
        # # (1) all()    QuerySet: [<Book: Book object>, <Book: Book object>]
        # book_list=Book.objects.all()
        # print(book_list)
        #
        # # (2) filter()   QuerySet
        # book_list=Book.objects.filter(price=123,title="python")
        # print(book_list)
        # book = Book.objects.filter(price=123, title="python")[0]
        # print(book)  # model对象
        #
        # # (3) get()  model对象  有且只有一个查询结果才有意义
        # book=Book.objects.get(price=12345)
        # print(book)
    
        #(4)  order_by  QuerySet
        # book_list=Book.objects.all().order_by("-id")
        # book_list=Book.objects.all().order_by("price")
        # print(book_list)
        # # (5) count
        # c = Book.objects.all().order_by("price").count()
        # print(c)
        # # (6)first() model对象
        # book=Book.objects.all().first()
        #
        # # (7)exists()
        # ret=Book.objects.all().exists()
        # if ret:
        #     print("Ok")
        # (8)values:QuerySet
    
        # ret=Book.objects.all().values("title","price")
        # print(ret) # <QuerySet [{'title': 'python'}, {'title': 'php'}]>
        # ret=Book.objects.all().values_list("title","price")
        # print(ret)# <QuerySet [('python', Decimal('123.00')), ('php', Decimal('122.00'))]>
        # (9)distinct
        # ret=Book.objects.all().values("price").distinct()
        # print(ret)
    
        #######################模糊查询#############################
        book_list=Book.objects.filter(title__startswith="py")
        book_list=Book.objects.filter(price__gt=120)
        return HttpResponse("OK")
    
    '''
       temp=[] 
       for obj in Book.objects.all():
           temp.append({
               "title":obj.title
               "price":obj.price
           })
    '''
    
    
    def books(reqeust):
    
        book_list=Book.objects.all()
    
        # 一对多查询
        # book_obj=Book.objects.filter(id=6).first()
        # print(book_obj.publish.name)
        # print(book_obj.publish.email)
    
        # 多对多的查询
        # book_obj = Book.objects.filter(id=6).first()
        # print(book_obj.author.all())
    
        return render(reqeust,"books.html",locals())
    
    
    def addbook(request):
    
        if request.method=="POST":
    
            title=request.POST.get("title")
            price=request.POST.get("price")
            date=request.POST.get("date")
            publish_id=request.POST.get("publish_id")
            author_id_list=request.POST.getlist("author_id_list")
            print("author_id_list",author_id_list)
            # 绑定书籍与出版社的一对多的关系
            obj=Book.objects.create(title=title,price=price,create_time=date,publish_id=publish_id)
            # 绑定书籍与作者的多对多的关系
            # 不可行方案
            # for author_id in author_id_list:
            #     A.objects.create(book_id=obj.pk,author_id=author_id)
            # 可行方案
            # obj.author.add(1,2,3)
            # obj.author.remove(1,2)
            # obj.author.clear()
            obj.authors.add(*author_id_list)
            return redirect("/books/")
        else:
            publish_list=Publish.objects.all()
            author_list=Author.objects.all()
            return render(request,"addbook.html",locals())
    
    def editbook(request,id):
        if request.method == "POST":
            title=request.POST.get("title")
            price=request.POST.get("price")
            date=request.POST.get("date")
            publish_id=request.POST.get("publish_id")
            author_id_list=request.POST.getlist("author_id_list")
            # QuerySet才能update
            Book.objects.filter(id=id).update(title=title,price=price,create_time=date,publish_id=publish_id)
            # 先清空与多值的关系,再添加多对多的关系
            Book.objects.get(id=id).authors.clear()
            Book.objects.get(id=id).authors.add(*author_id_list)
    # 等同于 book.authors.set(author_id_list)
    return redirect("/books/") publish_list = Publish.objects.all() author_list = Author.objects.all() edit_book=Book.objects.get(id=id) return render(request,"editbook.html",locals()) def delbook(request,id): Book.objects.filter(id=id).delete() return redirect("/books/")

    templates/books.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>书籍展示页</title>
        <style>
            .container{
                margin-top: 100px;
            }
        </style>
        <link rel="stylesheet" href="/static/bs/css/bootstrap.css">
    </head>
    <body>
        <div class="container">
            <div class="row">
                <div class="col-md-6 col-md-offset-3">
                    <a href="{% url 'add_book'%}"><button class="btn btn-primary">添加数据</button></a>
                    <table class="table table-bordered table-striped">
                        <thead>
                             <tr>
                                  <th>序号</th>
                                  <th>书名</th>
                                  <th>价格</th>
                                  <th>出版时间</th>
                                  <th>出版社</th>
                                  <th>作者</th>
                                  <th>操作</th>
                             </tr>
                        </thead>
                        <tbody>
                             {% for book in book_list %}
                             <tr>
                                 <td>{{ forloop.counter }}</td>
                                 <td>{{ book.title }}</td>
                                 <td>{{ book.price }}</td>
                                 <td>{{ book.create_time|date:"Y-m-d" }}</td>
                                 <td>{{ book.publish.name }}</td>
                                 <td>
                                     {% for author in book.authors.all %}
                                     {{ author.name }}
                                         {% if not forloop.last %}
                                         ,
                                         {% endif %}
                                     {% endfor %}
                                 </td>
                             <td>
                                 <a href="{% url 'edit_book' book.pk %}">编辑</a>
                                 <a href="{% url 'del_book' book.pk %}">删除</a>
                             </td>
                             </tr>
                             {% endfor %}
    
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    
    
    </body>
    </html>

    templates/editbook.html

    <!DOCTYPE html>
    <html lang="zh-cn">
    <head>
        <meta charset="UTF-8">
        <title>编辑书籍</title>
        <style>
            .container{
                margin-top: 100px;
            }
        </style>
        <link rel="stylesheet" href="/static/bs/css/bootstrap.css">
    </head>
    <body>
        <div class="container">
            <div class="row">
                <div class="col-md-6 col-md-offset-3">
                    <form action="{% url 'edit_book' id%}" method="post">
                        {% csrf_token %}
                        <p>书籍名称 <input type="text" name="title" value="{{ edit_book.title }}"></p>
                        <p>书籍价格 <input type="text" name="price" value="{{ edit_book.price }}"></p>
                        <p>出版日期 <input type="date" name="date" value="{{ edit_book.create_time|date:"Y-m-d" }}"></p>
                        <p>出版社 <select name="publish_id" id="">
                            {% for publish in publish_list %}
                                {% if edit_book.publish == publish %}
                                    <option selected value="{{ publish.id }}">{{ publish.name }}</option>
                                {% else %}
                                    <option value="{{ publish.id }}">{{ publish.name }}</option>
                                {% endif %}
                            {% endfor %}
    
                           </select>
                        </p>
    
                        <p>作者<select name="author_id_list" id="" multiple >
                            {% for author in author_list %}
                                {% if author in edit_book.authors.all %}
                                    <option selected value="{{ author.id }}">{{ author.name }}</option>
                                {% else %}
                                    <option value="{{ author.id }}">{{ author.name }}</option>
                                {% endif %}
    
                            {% endfor %}
                        </select>
    
                        </p>
                        <input type="submit" class="btn btn-default">
                    </form>
                </div>
            </div>
        </div>
    
    
    </body>
    </html>

    templates/addbook.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>新增书籍</title>
        <style>
            .container{
                margin-top: 100px;
            }
        </style>
        <link rel="stylesheet" href="/static/bs/css/bootstrap.css">
    </head>
    <body>
        <div class="container">
            <div class="row">
                <div class="col-md-6 col-md-offset-3">
                    <form action="{% url 'add_book'%}" method="post">
                        {% csrf_token %}
                        <p>书籍名称 <input type="text" name="title"></p>
                        <p>书籍价格 <input type="text" name="price"></p>
                        <p>出版日期 <input type="date" name="date"></p>
                        <p>出版社 <select name="publish_id" id="">
                            {% for publish in publish_list %}
                                <option value="{{ publish.pk }}">{{ publish.name }}</option>
                            {% endfor %}
    
                           </select>
                        </p>
    
                        <p>作者 <select name="author_id_list" id="" multiple>
                            {% for author in author_list %}
                                <option value="{{ author.pk }}">{{ author.name }}</option>
                            {% endfor %}
    
                           </select>
                        </p>
                        <input type="submit" class="btn btn-default">
                    </form>
                </div>
            </div>
        </div>
    
    
    </body>
    </html>
  • 相关阅读:
    web前端工程师
    java工程师
    原因原来默认预检测会检测是否存在多选框
    软件测试&安全测试高峰论坛
    安卓学习图
    为什么mongo中不能用int作为key
    历经小半宿吧。哎,终于搭建好了Linux-C的环境
    把昨晚写的东西完善了一下,还行,真差不多
    半宿了,仿写了个CList模板类,留着以后用吧
    今天复习了一下完成端口网络模型
  • 原文地址:https://www.cnblogs.com/shangdelu/p/8881513.html
Copyright © 2020-2023  润新知