Django创建并连接数据库(实现增删改查)--第二版

注意点一:

url里面的地址,不只是html页面,准确说是views视图里面对应的函数方法

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.css">
    <title>出版社列表</title>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-6 col-md-offset-3">
            <h2>出版社列表</h2>
            <table class="table table-condensed">
                <thead>
                <tr>
                    <th>ID</th>
                    <th>出版社名称</th>
                    <th>出版社地址</th>
                    <th>邮箱</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                    {% for publish in publish_list %}
                        <tr>
                            <td>{{ forloop.counter }}</td>
                            <td>{{ publish.name}}</td>
                            <td>{{ publish.addr }}</td>
                            <td>{{ publish.email }}</td>
                            <td>

                                <!--定义2个链接,点击之后实质是向服务端又提交了一个get请求,并且把对应那天数据的nid发送给服务端-->
                                <!--get方式携带参数到后台,例如?nid=123&name=yzz(后面可以跟多个),但是nid是唯一的,所以用nid-->
                                <!--会触发视图里面的删除方法,将要删除数据的nid当做参数传入-->
                                <a href="/delete_publish/?nid={{ publish.nid }}" class="btn btn-danger">删除</a>
                                <a href="/edit_publish/?nid={{ publish.nid }}" class="btn btn-success">编辑</a>
                            </td>
                        </tr>
                    
                    {% endfor %}
                    
                </tbody>
            </table>


        </div>
    </div>
</div>
</body>
</html>
publish_list.py配置辅助理解

 注意点二:

1.views.py里面配置的视图函数

2.注意get带参数的请求与post请求

3.多对多产生第三张表的方法,已经默认建好之后表的名字和字段的名字

from django.shortcuts import render,HttpResponse,redirect

# Create your views here.
from app01.models import *

#添加出版社
def add_publish(request):
    if request.method=='POST':
        name = request.POST.get('name')
        addr = request.POST.get('addr')
        email = request.POST.get('email')
        Publish.objects.create(name=name,addr=addr,email=email)

        #点击添加后信息重定向到查看出版社列表的方法界面
        return redirect('/publish_list/')   #跳转到查看界面,可以完成编辑和删除操作

    #如果是get请求默认就是添加出版社界面
    return render(request,"add_publish.html")

#查看出版社信息
def publish_list(request):
    publish_list=Publish.objects.all()
    return render(request,'publish_list.html',{'publish_list':publish_list})

#删除出版社信息
def delete_publish(request):
    nid=request.GET.get('nid')
    print(nid)  #是实际数据库里面的id值(不是{ forloop.counter }}页面上看到的设定的自动增长的值)
    # 通过filter过滤出nid为传入的nid,删除掉
    #filter功能相当与:select * from where id =2;
    ret=Publish.objects.filter(nid=nid)   #ret是个列表
    # 删除这些数据
    print(ret)   #<QuerySet [<Publish: Publish object>]>
    ret.delete()
    return redirect('/publish_list/')



#编辑出版社信息
def edit_publish(request):
    # post请求:是编辑完之后提交数据的请求
    if request.method=='POST':
        nid=request.POST.get('nid')
        name=request.POST.get('name')
        addr=request.POST.get('addr')
        email=request.POST.get('email')
        #先查找,再更新
        Publish.objects.filter(pk=nid).update(name=name, addr=addr, email=email)
        return redirect('/publish_list/')

    #Get请求:数据拿过来跳转到编辑页面
    nid=request.GET.get('nid')

    #Publish.objects.filter(nid=nid) 是个列表,类表的第一个值是对象
    # aa=Publish.objects.filter(nid=nid)
    # print(aa.__dict__) #{'model': <class 'app01.models.Publish'>, '_db': None, '_hints': {},..}
    publish=Publish.objects.filter(nid=nid).first() #publish是个对象
    print(publish)
    return render(request,'edit_publish.html',{'publish':publish})






#添加书名信息
def add_book(request):
    if request.method=='POST':
        name=request.POST.get('name')
        price=request.POST.get('price')
        pub_date=request.POST.get('pub_date')
        #添加表示出版社的id字段
        publish_id=request.POST.get('publish')

        #拿到对应的作者的列表,authors是个对象,传递的是每个对象对应的id号
        authors=request.POST.getlist('authors')  #authors是个列表
        book=Book.objects.create(name=name,price=price,pub_date=pub_date,publish_id=publish_id)

        #会在书与作者多对多关系产生的第三张表book_authors里面添加表记录
        book.authors.add(*authors)  #把每个作者的类表id打乱传入

        return redirect('/book_list/')

    #默认拿到出版社列表、作者列表
    publish_list = Publish.objects.all()
    author_list = Author.objects.all()
    return render(request,'add_book.html',{'publish_list':publish_list,'author_list':author_list})


def book_list(request):
    book_list=Book.objects.all()
    return  render(request,'book_list.html',{'book_list':book_list})


def delete_book(request):
    nid = request.GET.get('nid')
    ret = Book.objects.filter(nid=nid)  # ret是个列表
    ret.delete()
    return redirect('/book_list/')



def edit_book(request):
    if request.method=='POST':
        nid=request.POST.get('nid')
        name=request.POST.get('name')
        price=request.POST.get('price')
        pub_date=request.POST.get('pub_date')
        publish_id=request.POST.get('publish')
        authors=request.POST.getlist('authors')
        Book.objects.filter(pk=nid).update(name=name,price=price,pub_date=pub_date,publish_id=publish_id)
        book=Book.objects.filter(pk=nid).first()
        #重置authors的值(用于更新到第三张表里面),先删除原纪录再添加
        book.authors.set(authors)
        #相当于
        # book.authors.clear()
        # book.authors.add(*authors)
        return redirect('/book_list/')

    nid = request.GET.get('nid')
    book=Book.objects.filter(nid=nid).first()
    publish_list=Publish.objects.all()
    author_list=Author.objects.all()
    return render(request,'edit_book.html',{'book':book,'publish_list':publish_list,'author_list':author_list})
views.py

from django.db import models

# Create your models here.

#出版社数据库指定的字段及类型
class Publish(models.Model):
    nid=models.AutoField(primary_key=True)
    name=models.CharField(max_length=32)
    addr=models.CharField(max_length=64)
    # 也是varchar类型
    email=models.EmailField()

#作者数据中指定的字段及类型
class Author(models.Model):
    nid = models.AutoField(primary_key=True)
    name=models.CharField(max_length=32)
    age=models.IntegerField()

#图书数据库指定的字段及类型
class Book(models.Model):
    nid = models.AutoField(primary_key=True)
    name=models.CharField(max_length=32)
    price=models.DecimalField(max_digits=5,decimal_places=2)
    pub_date=models.DateField()

    #建立书与出版社一对多关系
    # to后面的那个表,可以不加引号,但是,要在前面定义(即Publish类要写在Book的前面)
    publish=models.ForeignKey(to='Publish',to_field='nid')  #创建完成表字段会是 publish_id

    #建立书与作者多对多关系
    #作用:针对对对多关系,创建建爱你出第三张表(代替了下面的3行代码)
    authors=models.ManyToManyField(to='Author')  #这是第三张表的名字:book_authors,包含的字段有book_id author_id


# class Book2Author(models.Model):
#     nid=models.AutoField(primary_key=True)
#     book=models.ForeignKey(to='Book',to_field='nid')
#     author=models.ForeignKey(to='Author',to_field='nid')
models.py数据库表的建立

注意点三:templates模本文件下面的一些配置文件

1.注意页面格式的书写

2.注意里面for循环的一个取值

3.get方法传参的应用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>新增图书</title>
    <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.css">
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-6 col-md-offset-3">
            <h2>新增图书</h2>
            <form action="/add_book/" method="post">
                <input type="hidden" name="nid" class="form-control" value="{{ publish.nid }}">
                <p>图书名称:<input type="text" name="name" class="form-control"></p>
                <p>价格:<input type="text" name="price" class="form-control" ></p>
                <p>出版日期:<input type="date" name="pub_date" class="form-control"></p>
                <p>出版社:
                    <!--循环出出版社列表,让那个让用户进行出版社名字,对应提交的就是对应出版社的id-->
                    <select name="publish" id="" class="form-control">
                        {% for publish in publish_list %}
                        <option value="{{ publish.nid }}">{{ publish.name }}</option>
                        {% endfor %}
                    </select>
                </p>
            <p>作者:
                <select name="authors" id="" multiple class="form-control">
                    {% for author in author_list %}
                        <option value="{{ author.nid }}">{{ author.name }}</option>

                    {% endfor %}


                </select>

            </p>


                <p><input type="submit" value="提交" class="form-control btn btn-success"></p>


            </form>

        </div>
    </div>
</div>
</body>
</html>
add_book.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>图书列表</title>
    <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.css">
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-6 col-md-offset-3">
            <h2>图书列表</h2>
            <table class="table table-condensed">
                <thead>
                <tr>
                    <th>ID</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.name}}</td>
                            <td>{{ book.price }}</td>
                            <td>{{ book.pub_date|date:'Y-m-d' }}</td>
                            <td>{{ book.publish.name }}</td>
                            <td>
                                {% for author in  book.authors.all  %}
                                    {{ author.name }}|
                                {% endfor %}

                            </td>

                            <td>
                                <a href="/delete_book/?nid={{ book.nid }}" class="btn btn-danger">删除</a>
                                <a href="/edit_book/?nid={{ book.nid }}" class="btn btn-success">编辑</a>
                            </td>
                        </tr>

                    {% endfor %}

                </tbody>
            </table>


        </div>
    </div>
</div>

</body>
</html>
book_list.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>编辑图书</title>
    <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.css">
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-6 col-md-offset-3">
            <h2>新增图书</h2>
            <form action="/edit_book/" method="post">
                <input type="hidden" name="nid" value="{{ book.nid }}">
                <p>图书名称:<input type="text" name="name" class="form-control" value="{{ book.name }}"></p>
                <p>价格:<input type="text" name="price" class="form-control" value="{{ book.price }}"></p>
                <p>出版日期:<input type="date" name="pub_date" class="form-control" value="{{ book.pub_date|date:"Y-m-d" }}"></p>
                <p>出版社:
                    <select name="publish" id="" class="form-control">
                    <!--判断,编辑时让编辑状态下图书对应的出版社默认就是后台对应的-->
                        {% for publish in publish_list %}
                            {% if book.publish == publish %}
                                <option selected value="{{ publish.nid }}">{{ publish.name }}</option>
                            {% else %}
                                <option value="{{ publish.nid }}">{{ publish.name }}</option>
                            {% endif %}

                        {% endfor %}
                    </select>
                </p>
                <p>作者:
                    <select name="authors" id="" multiple class="form-control">
                    <!--判断,编辑时让作者一栏和初始状态的书对应-->
                        {% for author in author_list %}
                            {% if author in book.authors.all %}
                                <option selected value="{{ author.nid }}">{{ author.name }}</option>
                            {% else %}
                                <option value="{{ author.nid }}">{{ author.name }}</option>
                            {% endif %}

                        {% endfor %}


                    </select>

                </p>


                <p><input type="submit" value="提交" class="form-control btn btn-success"></p>


            </form>

        </div>
    </div>
</div>
</body>
</html>
edit_book.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>新增出版社</title>
    <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.css">
</head>
<body>

<div class="container">
    <div class="row">
        <div class="col-md-6 col-md-offset-3">
            <h2>添加出版社</h2>
            <form action="/add_publish/" method="post">
                <p>出版社名称:<input type="text" name="name" class="form-control"></p>
                <p>出版社地址:<input type="text" name="addr" class="form-control"></p>
                <p>出版社邮箱:<input type="text" name="email" class="form-control"></p>
                <p><input type="submit" value="添加" class="form-control btn btn-success"></p>



            </form>

        </div>
    </div>
</div>

</body>
</html>
add_publish.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.css">
    <title>出版社列表</title>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-6 col-md-offset-3">
            <h2>出版社列表</h2>
            <table class="table table-condensed">
                <thead>
                <tr>
                    <th>ID</th>
                    <th>出版社名称</th>
                    <th>出版社地址</th>
                    <th>邮箱</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                    {% for publish in publish_list %}
                        <tr>
                            <td>{{ forloop.counter }}</td>
                            <td>{{ publish.name}}</td>
                            <td>{{ publish.addr }}</td>
                            <td>{{ publish.email }}</td>
                            <td>

                                <!--定义2个链接,点击之后实质是向服务端又提交了一个get请求,并且把对应那天数据的nid发送给服务端-->
                                <!--get方式携带参数到后台,例如?nid=123&name=yzz(后面可以跟多个),但是nid是唯一的,所以用nid-->
                                <!--会触发视图里面的删除方法,将要删除数据的nid当做参数传入-->
                                <a href="/delete_publish/?nid={{ publish.nid }}" class="btn btn-danger">删除</a>
                                <a href="/edit_publish/?nid={{ publish.nid }}" class="btn btn-success">编辑</a>
                            </td>
                        </tr>
                    
                    {% endfor %}
                    
                </tbody>
            </table>


        </div>
    </div>
</div>
</body>
</html>
publish_list.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>修改出版社</title>
    <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.css">
</head>
<body>


<div class="container">
    <div class="row">
        <div class="col-md-6 col-md-offset-3">
            <h2>修改出版社</h2>
            <form action="/edit_publish/" method="post">
                <!--{{ publish.nid }}:点击编辑时默认显示原来数据,在基础上进行修改-->
                <input type="hidden" name="nid" class="form-control" value="{{ publish.nid }}">
                <p>出版社名称:<input type="text" name="name" class="form-control" value="{{ publish.name }}"></p>
                <p>出版社地址:<input type="text" name="addr" class="form-control" value="{{ publish.addr }}"></p>
                <p>出版社邮箱:<input type="text" name="email" class="form-control" value="{{ publish.email }}"></p>
                <p><input type="submit" value="修改" class="form-control btn btn-success"></p>


            </form>

        </div>
    </div>
</div>
</body>
</html>
edit_publish.html

猜你喜欢

转载自www.cnblogs.com/yangzhizong/p/9581976.html
今日推荐