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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM