Django的form组件——ModelForm实战

2021-09-09

模型:

from django.db import models


class Book(models.Model):
    book_name = models.CharField(max_length=30)
    book_publisher = models.CharField(max_length=20)
    book_author = models.CharField(max_length=20)

    class Meta:
        db_table = 'book_tb'

  

 

路由:

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


urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/',views.index),     #首页的路由
    path('add/',views.add),         #添加数据的路由
    path('edit/',views.edit),       #编辑数据的路由
    path('delete/',views.delete)    #删除数据的路由
]

  

视图:

from django.shortcuts import render,HttpResponse,redirect
from django import forms
from app01.models import Book

#定义一个form表单的类,使用Book模型
class BookForm(forms.ModelForm):
    class Meta:
        model = Book
        fields = ['book_name','book_publisher','book_author']   #生成表单的时候显示的字段



#首页展示所有书籍(常规操作)
def index(request):
    books = Book.objects.all()
    return render(request,'index.html',{'books': books})



#添加书籍(使用ModelForm的功能)
def add(request):
    if request.method == 'GET':
        b_obj = BookForm()
        return render(request,'add.html',{'b_obj': b_obj})  #返回一个添加页面,展示一个空的form表单
    else:
        b_obj = BookForm(request.POST)  #当用户提交数据后实例化一个拥有提交了的数据的对象
        if b_obj.is_valid():            #如果数据通过校验
            b_obj.save()                #保存到数据库中,添加一条记录
        return redirect('/index/')      #提交成功后跳转到首页



#编辑书籍(使用ModelForm的功能)
def edit(request):
    if request.method == 'GET':
        id = request.GET.get('id')  #获取要编辑的书籍的id
        book = Book.objects.get(id=id)  #取出id值对应的书籍对象
        b_obj = BookForm(instance=book)  # ***这一步实例化的时候,需要传入书籍对象,生成表单的时候就会默认填充这些数据,这也是和添加操作唯一的不同之处
        return render(request,'edit.html',{'b_obj': b_obj})
    else:
        #除了 b_obj = BookForm(instance=book) ,其余操作和添加相同
        b_obj = BookForm(request.POST)
        if b_obj.is_valid():
            b_obj.save()
        return redirect('/index/')



#删除书籍(常规操作)
def delete(request):
    id = request.GET.get('id')  # 获取要删除的书籍的id
    book = Book.objects.get(id=id)  # 取出id值对应的书籍对象
    book.delete()      #从数据库中删除这个书籍对象
    return redirect('/index/')   #删除后跳转至首页

  

首页:index.html

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Index</title>
</head>
<body>
    <div style="width: 60%;margin-left: 200px;">
        <button><a href="/add/">添加</a></button>
        <table style="width: 100%">
            <tr>
                <th style="border: red 1px solid">ID</th>
                <th style="border: red 1px solid">书名</th>
                <th style="border: red 1px solid">出版社</th>
                <th style="border: red 1px solid">作者</th>
                <th style="border: red 1px solid">编辑</th>
                <th style="border: red 1px solid">删除</th>
            </tr>
            {% for book in books %}
                <tr>
                    <td style="border: red 1px solid">{{ book.id }}</td>
                    <td style="border: red 1px solid">{{ book.book_name }}</td>
                    <td style="border: red 1px solid">{{ book.book_publisher }}</td>
                    <td style="border: red 1px solid">{{ book.book_author }}</td>
                    <td style="border: red 1px solid"><button><a href="/edit/?id={{ book.id }}">编辑</a></button></td>  {# 需要传入要编辑的书籍的id #}
                    <td style="border: red 1px solid"><button><a href="/delete/?id={{ book.id }}">删除</a></button></td> {# 需要传入要删除的书籍的id #}
                </tr>
            {% endfor %}

        </table>
    </div>
</body>
</html>

  

添加页面:add.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>添加页面</title>
</head>
<body>
    <div style="width: 60%;margin-left: 200px;">
        <form action="" method="post">
            {% csrf_token %}
            <div>
                {{ b_obj.as_p }}
            </div>

            <input type="submit" value="提交">
        </form>
    </div>
</body>
</html>

  

编辑页面:edit.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>编辑页面</title>
</head>
<body>
    <div style="width: 60%;margin-left: 200px;">
        <form action="" method="post">
            {% csrf_token %}
            <div>
                {{ b_obj.as_p }}
            </div>

            <input type="submit" value="提交">
        </form>
    </div>
</body>
</html>

  

 

结果展示: