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>

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

<form action="{% url 'polls:add_publisher' %}" method="post">
    {% csrf_token %}
    <input type="text" name="publisher_name">
    <input type="submit" value="提交">
    <p >{{ 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>

<h2>编辑出版社</h2>

<form action="/polls/edit_publisher/" method="post">
    <input type="text" name="id" value="{{ publisher.id }}" >
    <input type="text" name="publisher_name" value="{{ publisher.name }}">
    <input type="submit" value="提交">
    <p >{{ 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>

<h2>所有的书籍都在这里!</h2>
<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>

<h2>添加书籍</h2>
<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>

<h2>编辑书籍</h2>

<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操作表一对多实战

网站标题:5、django操作表一对多实战
文章分享:https://www.cdcxhl.com/article22/pohpjc.html

成都网站建设公司_创新互联,为您提供品牌网站建设用户体验关键词优化网页设计公司网站营销建站公司

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

小程序开发