5、django操作表一對多實戰

表結構
5、django操作表一對多實戰
一、入口url設置
D:\mysite\mysite\urls.py

from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('polls/',include('polls.urls')),
    path('admin/', admin.site.urls),
]

二、polls應用url設置
D:\mysite\polls\urls.py

from django.urls import path

from . import views
app_name = 'polls'
urlpatterns = [

    #出版社相關的對應關係
        #出版社列表頁
    path('publisher_list/', views.published_list,name='published_list'),
        #添加出版社
    path('add_publisher/', views.add_publisher,name='add_publisher'),
        #刪除出版社
    path('delete_ublisher/', views.delete_publisher,name='delete_publisher'),
        #編輯出版社
    path('edit_publisher/', views.edit_publisher,name='edit_publisher'),

    #書相關的對應關係
        #書籍列表頁
    path('book_list/', views.book_list,name='book_list'),
        #添加書籍
    path('add_book/', views.add_book,name='add_book'),  
        #刪除書籍
    path('delete_book/', views.delete_book,name='delete_book'),  
        #編輯書籍
    path('edit_book/', views.edit_book,name='edit_book'),  

]

三、modes配置
D:\mysite\polls\models.py

from django.db import models
#出版社
class Publisher(models.Model):
    id = models.AutoField(primary_key=True)  # 自增的ID主鍵
    #創建一個varchar(64)的唯一的不爲空的字段
    name = models.CharField(max_length=64, null=False)

#書
class Book(models.Model):
    id = models.AutoField(primary_key=True)  # 自增的ID主鍵
    #創建一個varchar(64)的唯一的不爲空的字段
    title = models.CharField(max_length=64, null=False, unique=True)
    #和出版社關聯的外鍵字段
    publisher = models.ForeignKey(to="Publisher", on_delete=models.CASCADE)
#建建表
python manage.py makemigrations
python manage.py migrate

四靜態文件設置

####################出版社html#########################
#出版社列表頁D:\mysite\polls\templates\polls\publisher_list.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>出版社列表</title>
</head>
<body>

<a href="/polls/add_publisher/">添加新的出版社</a>

<table border="1">
    <thead>
        <tr>
            <th>序號</th>
            <th>ID</th>
            <th>出版社名稱</th>
            <th>操作</th>
        </tr>
    </thead>
    <tbody>
        {% for publisher in publisher_list %}
            <tr>
                <td>{{ forloop.counter }}</td>
                <td>{{ publisher.id }}</td>
                <td>{{ publisher.name }}</td>
                <td>
                    <a href="/polls/delete_publisher/?id={{ publisher.id }}">刪除</a>
                    <a href="/polls/edit_publisher/?id={{ publisher.id }}">編輯</a>
                </td>
            </tr>
        {% endfor %}
    </tbody>
</table>

</body>
</html>

#添加出版社列表頁D:\mysite\polls\templates\polls\add_publisher.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>添加出版社</title>
</head>
<body>

<h1>添加出版社</h1>

<form action="{% url 'polls:add_publisher' %}" method="post">
    {% csrf_token %}
    <input type="text" name="publisher_name">
    <input type="submit" value="提交">
    <p style="color: red">{{ error }}</p>
</form>

</body>
</html>

#編輯出版社列表頁D:\mysite\polls\templates\polls\edit_publisher.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>編輯出版社</title>
</head>
<body>

<h1>編輯出版社</h1>

<form action="/polls/edit_publisher/" method="post">
    <input type="text" name="id" value="{{ publisher.id }}" style="display: none">
    <input type="text" name="publisher_name" value="{{ publisher.name }}">
    <input type="submit" value="提交">
    <p style="color: red">{{ error }}</p>
</form>

</body>
</html>

####################書籍html#########################
#書籍列表頁D:\mysite\polls\templates\polls\book_list.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>書籍列表</title>
</head>
<body>

<h1>所有的書籍都在這裏!</h1>
<a href="/polls/add_book/">添加書籍</a>

<table border="1">
    <thead>
        <tr>
            <th>id</th>
            <th>title</th>
            <th>publisher</th>
            <th>操作</th>
        </tr>
    </thead>
    <tbody>
        {% for i in all_book %}
            <tr>
            <td>{{ i.id }}</td>
            <td>{{ i.title }}</td>
            <td>{{ i.publisher.name }}</td>
            <td>
                <a href="/polls/delete_book/?id={{ i.id }}">刪除</a>
                <a href="/polls/edit_book/?id={{ i.id }}">編輯</a>
            </td>
            </tr>
        {% endfor %}
    </tbody>
</table>
</body>
</html>

#添加書籍D:\mysite\polls\templates\polls\add_book.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>添加書籍</title>
</head>
<body>

<h1>添加書籍</h1>
<form action="/polls/add_book/" method="post">
    <p>
        書名:<input type="text" name="book_title">
    </p>
    <p>
        出版社:
        <select name="publisher" >
            {% for publisher in publisher_list %}
                <option value="{{ publisher.id }}">{{ publisher.name }}</option>
            {% endfor %}
        </select>
    </p>
    <p>
         <input type="submit" value="提交">
    </p>

</form>

</body>
</html>

#編輯書籍
D:\mysite\polls\templates\polls\edit_book.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>編輯書籍</title>
</head>
<body>

<h1>編輯書籍</h1>

<form action="/polls/edit_book/" method="post">
    <input type="hidden"  name="id" value="{{ book_obj.id }}">
    <p>
        書名:
        <input type="text" name="book_title" value="{{ book_obj.title }}">
    </p>
    <p>
        出版社:
        <select name="publisher">

            {% for publisher in publisher_list %}

                {% if book_obj.publisher_id == publisher.id %}
                    {#  當前書籍關聯的出版社才默認選中#}
                    <option selected value="{{ publisher.id }}">{{ publisher.name }}</option>
                {% else %}
                    {# 其他的出版社不選中 #}
                    <option value="{{ publisher.id }}">{{ publisher.name }}</option>
                {% endif %}
            {% endfor %}

        </select>
    </p>
    <p>
        <input type="submit" value="提交">
    </p>
</form>

</body>
</html>

五、後端處理D:\mysite\polls\views.py

from django.shortcuts import render,redirect,ttpResponse
from .models import Question,Publisher
from polls import models

#出版社列表
def published_list(request):
    ret = Publisher.objects.all().order_by("id")
    return render(request,"polls/publisher_list.html",{"publisher_list": ret})

#添加新的出版社
def add_publisher(request):
    error_msg = ""
    #如果是POST請求,我就取到用戶填寫的數據
    print(request.method)
    if request.method == "POST":
        new_name = request.POST.get("publisher_name", None)
        if new_name:
            # 通過ORM去數據庫裏新建一條記錄
            Publisher.objects.create(name=new_name)
            #引導用戶訪問出版社列表頁,查看是否添加成功  --> 跳轉
            return redirect("/polls/publisher_list/")
        else:
            error_msg = "出版社名字不能爲空!"
    #用戶第一次來,我給他返回一個用來填寫的HTML頁面
    return render(request, "polls/add_publisher.html", {"error": error_msg})

#刪除出版社
def delete_publisher(request):
    print(request.GET)
    print("=" * 120)
    #刪除指定的數據
    #1. 從GET請求的參數裏面拿到將要刪除的數據的ID值
    del_id = request.GET.get("id", None)  # 字典取值,娶不到默認爲None
    #如果能取到id值
    if del_id:
        # 去數據庫刪除當前id值的數據
        #根據id值查找到數據
        del_obj = models.Publisher.objects.get(id=del_id)
        #刪除
        del_obj.delete()
        #返回刪除後的頁面,跳轉到出版社的列表頁,查看刪除是否成功
        return redirect("/polls/publisher_list/")
    else:
        return HttpResponse("要刪除的數據不存在!")

#編輯出版社
def edit_publisher(request):
    #用戶修改完出版社的名字,點擊提交按鈕,給我發來新的出版社名字
    if request.method == "POST":
        print(request.POST)
        #取新出版社名字
        edit_id = request.POST.get("id")
        new_name = request.POST.get("publisher_name")
        #更新出版社
        #根據id取到編輯的是哪個出版社
        edit_publisher = models.Publisher.objects.get(id=edit_id)
        edit_publisher.name = new_name
        edit_publisher.save()  # 把修改提交到數據庫
        #跳轉出版社列表頁,查看是否修改成功
        return redirect("/polls/publisher_list/")
    #從GET請求的URL中取到id參數
    edit_id = request.GET.get("id")
    if edit_id:
        #獲取到當前編輯的出版社對象
        publisher_obj = models.Publisher.objects.get(id=edit_id)
        return render(request, "polls/edit_publisher.html", {"publisher": publisher_obj})
    else:
        error_msg = "編輯的出版社不存在!"
        return HttpResponse("編輯的出版社不存在!")

#展示書的列表
def book_list(request):
    # 去數據庫中查詢所有的書籍
    all_book = models.Book.objects.all()
    #在HTML頁面完成字符串替換(渲染數據)
    return render(request, "polls/book_list.html", {"all_book": all_book})

#添加書籍
def add_book(request):
    if request.method == "POST":
        new_title = request.POST.get("book_title")
        new_publisher_id = request.POST.get("publisher")
        #創建新書對象,自動提交
        models.Book.objects.create(title=new_title, publisher_id=new_publisher_id)
        #返回到書籍列表頁
        return redirect("/polls/book_list/")

    #取到所有的出版社
    ret = models.Publisher.objects.all()
    return render(request, "polls/add_book.html", {"publisher_list": ret})

#刪除書籍
def delete_book(request):
    #從URL裏面獲取要刪除的書籍的id值
    delete_id = request.GET.get("id")  # 從URL裏面取數據
    #去刪除數據庫中刪除指定id的數據
    models.Book.objects.get(id=delete_id).delete()
    #返回書籍列表頁面, 查看是否刪除成功
    return redirect("/polls/book_list/")

#編輯書籍
def edit_book(request):
    if request.method == "POST":
        # 從提交的數據裏面取,書名和書關聯的出版社
        edit_id = request.POST.get("id")
        new_title = request.POST.get("book_title")
        new_publisher_id = request.POST.get("publisher")
        #更新
        edit_book_obj = models.Book.objects.get(id=edit_id)
        edit_book_obj.title = new_title  # 更新書名
        edit_book_obj.publisher_id = new_publisher_id  # 更新書籍關聯的出版社
        #將修改提交到數據庫
        edit_book_obj.save()
        #返回書籍列表頁面,查看是否編輯成功
        return redirect("/polls/book_list/")

    #返回一個頁面,讓用戶編輯書籍信息
    #取到編輯的書的id值
    edit_id = request.GET.get("id")
    #根據id去數據庫中把具體的書籍對象拿到
    edit_book_obj = models.Book.objects.get(id=edit_id)
    ret = models.Publisher.objects.all()
    return render(
        request,
        "polls/edit_book.html",
        {"publisher_list": ret, "book_obj": edit_book_obj}
    )

訪問出版社列表頁
http://127.0.0.1:8000/polls/publisher_list/
5、django操作表一對多實戰

添加出版社頁
http://127.0.0.1:8000/polls/add_publisher/
5、django操作表一對多實戰

編輯出版社
http://127.0.0.1:8000/polls/edit_publisher/?id=1
5、django操作表一對多實戰

訪問書籍列表頁
http://127.0.0.1:8000/polls/book_list/
5、django操作表一對多實戰

添加書籍頁
http://127.0.0.1:8000/polls/add_book/
5、django操作表一對多實戰

編輯書籍頁
http://127.0.0.1:8000/polls/edit_book/?id=5
5、django操作表一對多實戰

打開數據庫視圖查看
5、django操作表一對多實戰

5、django操作表一對多實戰

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章