Django自学练习---书籍的增删改查

project目录

在这里插入图片描述

urls.py

from django.contrib import admin
from django.urls import path
from publisher import views


urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.publisher_list),
    path('publisher_list/', views.publisher_list),
    path('add_publisher/', views.add_publisher),
    path('del_publisher/', views.del_publisher),
    path('edit_publisher/', views.edit_publisher),
    path('book_list/', views.book_list),
    path('add_book/', views.add_book),
    path('del_book/', views.del_book),
    path('edit_book/', views.edit_book),
]

models.py

from django.db import models


class Publisher(models.Model):
    pid = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32, unique=True)

    def __str__(self):
        return '{} - {}'.format(self.pid, self.name)


class Book(models.Model):
    name = models.CharField(max_length=32, unique=True)
    pub = models.ForeignKey('Publisher', on_delete=models.CASCADE)

views.py


# 展示书籍
def book_list(request):
    #     获取所有的书籍对象
    books = models.Book.objects.all()
    # 返回页面
    return render(request, 'book_list.html', {'books': books})


# 新增书籍
def add_book(request):
    if request.method == 'POST':
        #     获取提交的数据
        book_name = request.POST.get('book_name')
        pub_id = request.POST.get('pub_id')
        #     插入数据库
        # 这里的参数名pub是book表里的pub_id字段,由于pub是外键,所以pycharm自动在pub后面加了_id,需要注意,参数名不要写成pub_id
        # models.Book.objects.create(name=book_name, pub=models.Publisher.objects.get(pk=pub_id))
        # 最好用下面的写法,直接把book表里的pub_id赋值上面从request.POST里get到的pub_id
        models.Book.objects.create(name=book_name, pub_id=pub_id)
        # # 跳转到book_list页面
        return redirect('/book_list/')
    # 查询所有出版社信息
    all_publishers = models.Publisher.objects.all().order_by('pid')
    return render(request, 'add_book.html', {'all_publishers': all_publishers})


# 删除书籍
def del_book(request):
    # 获取要删除对象的id
    book_pk = request.GET.get('pk')
    # 在数据库中查询对应的对象,并删除
    models.Book.objects.filter(id=book_pk).delete()
    # 跳转到book_list展示页面
    return redirect('/book_list/')


# 编辑书籍
def edit_book(request):
    # 查询要编辑书籍的对象
    book_id = request.GET.get('pk')
    edit_book_obj = models.Book.objects.get(id=book_id)
    if request.method == 'POST':
        # 获取新提交的数据
        book_name = request.POST.get('book_name')
        pub_id = request.POST.get('pub_id')
        # 编辑书籍
        edit_book_obj.name = book_name
        edit_book_obj.pub_id = pub_id
        # 保存到数据库
        edit_book_obj.save()
    #     重定向到book_list展示页面
        return redirect('/book_list/')


    # 查询所有出版社信息
    all_publishers = models.Publisher.objects.all().order_by('pid')
    # 返回edit_book页面
    return render(request, 'edit_book.html' , {'edit_book_obj': edit_book_obj , 'all_publishers': all_publishers})

add_book.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="" method="post">
    <p>
        书名:<input type="text" name="book_name">
    </p>
    <p>
        出版社:
        <select name="pub_id" id="">
            {% for all_publisher in all_publishers %}
                <option value="{{ all_publisher.pk }}">{{ all_publisher.name }}</option>
            {% endfor %}
        </select>
    </p>
    <button>提交</button>
</form>
</body>
</html>

edit_book.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="" method="post">
    <p>
        书名:<input type="text" name="book_name" value="{{ edit_book_obj.name }}">
    </p>
    <p>
        出版社:
        <select name="pub_id" id="">
            {% for all_publisher in all_publishers %}
                {% if all_publisher == edit_book_obj.pub %}
                    <option selected value="{{ all_publisher.pk }}">{{ all_publisher.name }}</option>
                {% else %}
                    <option value="{{ all_publisher.pk }}">{{ all_publisher.name }}</option>
                {% endif %}

            {% endfor %}
        </select>
    </p>
    <button>提交</button>
</form>
</body>
</html>

book_list.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<table>
    <thead>
    <tr>
        <th>序号</th>
        <th>ID</th>
        <th>书名</th>
        <th>出版社</th>
    </tr>
    </thead>
    <tbody>
    {% for book in books %}
        <tr>
        <td>{{ forloop.counter }}</td>
        <td>{{ book.id }}</td>
        <td>{{ book.name }}</td>
        <td>{{ book.pub.name }}</td>
        <td>
            <a  href="/del_book/?pk={{ book.pk }}">删除</a>
            <a  href="/edit_book/?pk={{ book.pk }}">编辑</a>
        </td>
        </tr>
    {% endfor %}
    
    </tbody>
</table>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值