Django项目实战(一):图书管理系统---第三阶段---添加作者、出版社管理系统

下面是小凰凰的简介,看下吧!
人生态度:珍惜时间,渴望学习,热爱音乐,把握命运,享受生活
学习技能:网络 -> 云计算运维 -> python全栈( 当前正在学习中)
您的点赞、收藏、关注是对博主创作的最大鼓励,在此谢过!
有相关技能问题可以写在下方评论区,我们一起学习,一起进步。
后期会不断更新python全栈学习笔记,秉着质量博文为原则,写好每一篇博文。

文章目录

  • 一、效果展示
    • 1、图书管理系统
    • 2、作者管理系统
    • 3、出版社管理系统
  • 二、项目目录展示
  • 三、项目源码
    • 1、models.py
    • 2、urls.py
    • 3、views.py
    • 4、模板
        • (1)图书管理系统相关
            • 【1】index.html
            • 【2】add.html
            • 【3】edit.html
        • (2)作者管理系统相关
            • 【1】author_view.html
            • 【2】author_edit.html
        • (3)出版社管理系统相关
            • 【1】publisher_view.html
  • 四、项目心得总结
    • 1、input框对手机号、年龄、email的输入限制方法

一、效果展示

1、图书管理系统

Django项目实战(一):图书管理系统---第三阶段---添加作者、出版社管理系统_第1张图片

图书管理系统功能和第二阶段一样!就不多说!

2、作者管理系统

3、出版社管理系统

相比第二阶段改进点添加了作者、出版社管理系统

项目不足之处:
所有人进来,都能编辑删除添加书籍,缺少登录功能,应该只有登录之后的人才能进行书籍管理!

二、项目目录展示

Django项目实战(一):图书管理系统---第三阶段---添加作者、出版社管理系统_第2张图片

大致流程:
1、先把项目所用数据库准备好,改settings、\_\_init__文件把数据库连接好
2、然后设置url和视图函数映射关系,视图函数通过操作数据库,返回模板语法渲染好的页面,或者临时重定向到其他url对应的视图函数(我这里临时重定向的全是主页,因为数据修改完,就跳转到主页展示修改后的效果嘛)!
3、无论是模板中的html,还是视图函数都不要采用硬编码url,都应该使用name反向解析!

三、项目源码

1、models.py

相比第二阶段模型不变,也就是数据库不变!

from django.db import models


# Create your models here.
class Book(models.Model):
    name = models.CharField(max_length=30)
    price = models.IntegerField()
    pub_date = models.DateField()
    authors = models.ManyToManyField(to="Authors")  # 多对多
    publish = models.ForeignKey(to="Publisher", on_delete=models.CASCADE)  # 一对多,只有外键才有级联删除这一说。多对多是另外开一张表,不存在

    def __str__(self):
        return self.name


class Authors(models.Model):
    name = models.CharField(max_length=30)
    age = models.IntegerField()
    ad = models.OneToOneField(to="AuthorDetail", on_delete=models.CASCADE)

    def __str__(self):
        return self.name


class AuthorDetail(models.Model):
    email = models.EmailField()
    tel_phone = models.IntegerField()


class Publisher(models.Model):
    name = models.CharField(max_length=30)
    email = models.EmailField()

    def __str__(self):
        return self.name

这里面的AuthorDetail表,只是为了练习作者与作者详细之间的OneToOneField关系!对图书管理系统并没有实际意义!但是本阶段引入作者管理系统,它就有意义了!

2、urls.py

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.book_view, name='book_view'),
    path('books/add', views.book_add, name='book_add'),
    path('author/', views.author_view, name='author_view'),
    path('author/add/', views.author_add, name='author_add'),
    path('publisher/', views.publisher_view, name='publisher_view'),
    path('publisher/add/', views.publisher_add, name='publisher_add'),
    re_path('books/del/(?P[0-9]+)/', views.book_del, name='book_del'),
    re_path('books/edit/(?P[0-9]+)/', views.book_edit, name='book_edit'),
    re_path('author/del/([0-9]+)', views.author_del, name='author_del'),
    re_path('author/edit/([0-9]+)', views.author_edit, name='author_edit'),
    re_path('publisher/del/([0-9]+)', views.publisher_del, name='publisher_del')
    # 出版社信息很少,因此就没写编辑功能了!

3、views.py

from django.shortcuts import render
from app01.models import Book, Publisher, Authors, AuthorDetail
from django.shortcuts import redirect, reverse
from django.http import HttpResponse
import json


# Create your views here.
def book_view(request):
    book_list = Book.objects.all()
    return render(request, "index.html", {'book_list': book_list})


def book_add(request):
    if request.method == 'GET':
        publisher_list = Publisher.objects.all()
        author_list = Authors.objects.all()
        return render(request, 'add.html', {'publisher_list': publisher_list, 'author_list': author_list})
    else:
        name = request.POST.get('name')
        price = request.POST.get('price')
        pub_date = request.POST.get('pub_date')
        publisher_id = request.POST.get('publisher_id')
        authors_id = request.POST.getlist('authors_id[]')  # 这里得到的是一个author列表
        book = Book.objects.create(name=name, price=price, pub_date=pub_date, publish_id=publisher_id)
        book.authors.add(*authors_id)  # *号:列表打散
        return redirect(reverse('book_view'))


def book_del(request, del_book_id):
    response = {'status': True}
    try:
        Book.objects.get(pk=del_book_id).delete()
    except Exception:
        response['status'] = False
    return HttpResponse(json.dumps(response))


def book_edit(request, edit_book_id):
    book_obj = Book.objects.filter(pk=edit_book_id).first()
    if request.method == 'GET':
        publisher_list = Publisher.objects.all()
        author_list = Authors.objects.all()
        return render(request, 'edit.html',
                      {'book_obj': book_obj, 'publisher_list': publisher_list, 'author_list': author_list})
    else:
        name = request.POST.get('name')
        price = request.POST.get('price')
        pub_date = request.POST.get('pub_date')
        publisher_id = request.POST.get('publisher_id')
        authors_id = request.POST.getlist('authors_id[]')
        Book.objects.update(name=name, price=price, pub_date=pub_date, publish_id=publisher_id)
        book_obj.authors.set(*authors_id)
        return redirect(reverse('book_view'))


def author_view(request):
    author_list = Authors.objects.all()
    return render(request, 'author_view.html', {'author_list': author_list})


def author_add(request):
    name = request.POST.get('name')
    age = request.POST.get('age')
    email = request.POST.get('email')
    tel_number = request.POST.get('tel_number')
    ad_obj = AuthorDetail.objects.create(email=email, tel_phone=tel_number)
    Authors.objects.create(name=name, age=age, ad_id=ad_obj.pk)
    return redirect(reverse('author_view'))


def author_del(request, del_author_id):
    response = {'status': True}
    try:
        Authors.objects.get(pk=del_author_id).delete()
    except Exception:
        response['status'] = False
    return HttpResponse(json.dumps(response))


def author_edit(request, edit_author_id):
    author_obj = Authors.objects.get(pk=edit_author_id)
    if request.method == 'GET':
        return render(request, 'author_edit.html', {'author_obj': author_obj})
    else:
        name = request.POST.get('name')
        age = request.POST.get('age')
        email = request.POST.get('email')
        tel_number = request.POST.get('tel_number')
        AuthorDetail.objects.filter(pk=author_obj.ad_id).update(email=email, tel_phone=tel_number)
        Authors.objects.filter(pk=edit_author_id).update(name=name, age=age)
        return redirect(reverse('author_view'))


def publisher_view(request):
    publisher_list = Publisher.objects.all()
    return render(request, 'publisher_view.html', {'publisher_list': publisher_list})


def publisher_add(request):
    name = request.POST.get('name')
    email = request.POST.get('email')
    Publisher.objects.create(name=name, email=email)
    return redirect(reverse('publisher_view'))


def publisher_del(request, del_publisher_id):
    print(del_publisher_id)
    response = {'status': True}
    try:
        Publisher.objects.get(pk=del_publisher_id).delete()
    except Exception as e:
        response['status'] = False
    return HttpResponse(json.dumps(response))

4、模板

(1)图书管理系统相关

【1】index.html

<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    {% block page_title %}
        <title>图书管理系统title>
    {% endblock %}
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .table_area {
            width: 800px;
            position: absolute;
            top: 150px;
            left: 250px;
        }

        .add_btn {
            font-size: 18px;
            font-family: "Kaiti SC";
            font-weight: bolder;
        }

        .sys-menu {
            position: relative;
            top: auto;
            left: 35px;
            width: 150px;
            height: 200px;
        }

        .page_top {
            background-color: #146896;
            width: 100%;
            height: 50px;
        }

        .panel-heading {
            text-align: center;
            font-weight: bolder;
        }

        .panel-body {
            text-align: center;
            width: 100%;
        }

        .panel-body > a {
            text-decoration: none;
        }

        .panel-body > a:hover {
            color: skyblue;
        }

        .active{
            background-color: blanchedalmond;
        }

        #exampleModalLabel{
            font-family: "Kaiti SC";
            font-size: 20px;
            font-weight: bolder;
        }
    style>
head>
<body>
<div class="page_top">div>
<div class="panel panel-default sys-menu nav nav-pills">
    <div class="panel-heading">
        功能系统
    div>
{% block sys_view %}
    <div class="panel-body active">
        <a href="{% url 'book_view' %}">图书管理系统a>
    div>
    <div class="panel-body">
        <a href="{% url 'author_view' %}">作者管理系统a>
    div>
    <div class="panel-body">
        <a href="{% url 'publisher_view' %}">出版社管理系统a>
    div>
{% endblock %}
div>
{% block master_content %}
    <div class="table_area">
        {% csrf_token %}
        <table class="table table-hover">
            <thead>
            <tr>
                <th>书籍编号th>
                <th>书名th>
                <th>价格th>
                <th>出版时间th>
                <th>出版社th>
                <th>作者th>
                <th>操作th>
            tr>
            thead>
            <tbody>
            {% for book_obj in book_list %}
                <tr>
                    <td>{{ forloop.counter }}td>
                    <td>{{ book_obj.name }}td>
                    <td>{{ book_obj.price }}td>
                    <td>{{ book_obj.pub_date|date:'Y-m-d' }}td>
                    <td>{{ book_obj.publish.name }}td>
                    <td>
                        {% for author_obj in book_obj.authors.all %} 
                            {% if forloop.last %}
                                
                                {{ author_obj }}
                            {% else %}
                                {{ author_obj }},
                            {% endif %}

                        {% endfor %}
                    td>
                    <td>
                        <a href="{% url 'book_edit' book_obj.pk %}" class="btn btn-warning btn-xs">编辑a>
                        
                        <a id="del_book" class="btn btn-danger btn-xs" book_id={{ book_obj.pk }}>删除a>
                    td>
                tr>
                {% if forloop.last and forloop.counter > 0 %}
                    <tr>
                        <td colspan="7">
                            <a href="{% url 'book_add' %}" class="btn btn-info btn-xs form-control add_btn">添加书籍a>
                        td>
                    tr>
                {% endif %}
            {% empty %}
                <tr align="center">
                    <td colspan="7">
                        暂未上架任何书籍... <br>
                        <span>请点击:<a href="{% url 'book_add' %}" class="btn btn-info btn-xs">添加书籍a>span>
                    td>
                tr>
            {% endfor %}
            tbody>
        table>
    div>
{% endblock %}
body>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js">script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js">script>
{% block script_area %}
    <script>
        $(function () {
            $("tbody").on('click', '#del_book', function () {
                let $ele = $(this).parent().parent()
                $.ajax({
                    url: `/books/del/${$(this).attr('book_id')}/`,
                    type: "post",
                    data: {
                        csrfmiddlewaretoken: $("input[name='csrfmiddlewaretoken']").val()
                    },
                    success: function(response) {
                        response = JSON.parse(response)
                        if (response["status"] == true) {
                            $ele.remove()
                        } else {
                            alert('书籍删除失败!请重试')
                        }
                    }
                })
            })
        })
    script>
{% endblock %}
html>
【2】add.html

<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>图书管理系统title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .form-area {
            width: 600px;
            position: absolute;
            top: 130px;
            left: 300px;
        }

        h3 {
            position: relative;
            left: 270px;
            margin-bottom: 20px;
            font-family: "Kaiti SC";
            font-weight: bold;
        }

        .center-block {
            position: relative;
            left: 50px;
        }

        .author_add {
            position: relative;
            top: 20px;
        }

        #inputauthor {
            height: 75px;
        }
    style>
head>
<body>
<div class="form-area">
    {% block form_title %}
        <h3>书籍添加信息表h3>
    {% endblock form_title %}
    {% block form_head %}
        <form class="form-horizontal" action="{% url 'book_add' %}" method="post">
    {% endblock form_head %}
    {% csrf_token %}
    <div class="form-group">
        <label for="inputname" class="col-sm-2 control-label">书名label>
        <div class="col-sm-10">
            {% block inputname %}
                <input type="text" class="form-control" id="inputname" placeholder="请输入书籍名称" name="name">
            {% endblock inputname %}
        div>
    div>
    <div class="form-group">
        <label for="inputprice" class="col-sm-2 control-label">价格label>
        <div class="col-sm-10">
            {% block inputprice %}
                <input type="text" class="form-control" id="inputprice" placeholder="请输入价格" name="price">
            {% endblock inputprice %}
        div>
    div>
    <div class="form-group">
        <label for="input_pub_date" class="col-sm-2 control-label">出版时间label>
        <div class="col-sm-10">
            {% block input_pub_date %}
                <input type="date" class="form-control" id="input_pub_date" name="pub_date">
            {% endblock input_pub_date %}
        div>
    div>
    <div class="form-group">
        <label for="inputpublisher" class="col-sm-2 control-label">出版社label>
        <div class="col-sm-10">
            {% block inputpublisher %}
                <select name="publisher_id" id="inputpublisher" class="form-control">
                    {% for publish_obj in publisher_list %}
                        <option value="{{ publish_obj.pk }}">{{ publish_obj }}option>
                    {% endfor %}
                select>
            {% endblock inputpublisher %}
        div>
    div>
    <div class="form-group">
        <label for="inputauthor" class="col-sm-2 control-label author_add">作者label>
        <div class="col-sm-10">
            {% block inputauthor %}
                <select name="authors_id[]" id="inputauthor" class="form-control" multiple>
                    {% for author_obj in author_list %}
                        <option value="{{ author_obj.pk }}">{{ author_obj }}option>
                    {% endfor %}
                select>
            {% endblock inputauthor %}
        div>
    div>
    {% block submit %}
        <input type="submit" class="btn btn-success center-block" value="提交">
    {% endblock submit %}
    {% block form-tail %}
        form>
    {% endblock form-tail %}
div>
body>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js">script>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js">script>
html>
【3】edit.html

由于本页面和add.html及其相似,因此这里采用了模板继承

{% extends 'add.html' %}
{% block form_title %}
    <h3>书籍信息编辑表</h3>
{% endblock form_title %}

{% block form_head %}
    <form class="form-horizontal" action="{% url 'book_edit' book_obj.pk %}" method="post">
{% endblock form_head %}

{% block inputname %}
    <input type="text" class="form-control" id="inputname" name="name" value="{{ book_obj.name }}">
{% endblock inputname %}

{% block inputprice %}
    <input type="text" class="form-control" id="inputprice" name="price" value="{{ book_obj.price }}">
{% endblock inputprice %}

{% block input_pub_date %}
    <input type="date" class="form-control" id="input_pub_date" name="pub_date" value="{{ book_obj.pub_date|date:'Y-m-d' }}">
{% endblock input_pub_date %}

{% block inputpublisher %}
    <select name="publisher_id" id="inputpublisher" class="form-control">
        {% for publish_obj in publisher_list %}
            {% if book_obj.publish == publish_obj %}
                <option value="{{ publish_obj.pk }}" selected>{{ publish_obj }}</option>
            {% else %}
                <option value="{{ publish_obj.pk }}">{{ publish_obj }}</option>
            {% endif %}
        {% endfor %}
    </select>
{% endblock inputpublisher %}

{% block inputauthor %}
    <select name="authors_id[]" id="inputauthor" multiple class="form-control">
        {% for author_obj in author_list %}
            {% if author_obj in book_obj.authors.all %}
                <option value="{{ author_obj.pk }}" selected>{{ author_obj }}</option>
            {% else %}
                <option value="{{ author_obj.pk }}">{{ author_obj }}</option>
            {% endif %}
        {% endfor %}
    </select>
{% endblock inputauthor %}

{% block submit %}
    <input type="submit" class="btn btn-success center-block" value="提交修改">
{% endblock submit %}

{% block form-tail %}
    </form>>
{% endblock form-tail %}

(2)作者管理系统相关

【1】author_view.html
{% extends 'index.html' %}
{% block page_title %}
    <title>作者管理系统</title>
{% endblock %}
{% block sys_view %}
    <div class="panel-body">
        <a href="{% url 'book_view' %}">图书管理系统</a>
    </div>
    <div class="panel-body active">
        <a href="{% url 'author_view' %}">作者管理系统</a>
    </div>
    <div class="panel-body">
        <a href="{% url 'publisher_view' %}">出版社管理系统</a>
    </div>
{% endblock sys_view %}
{% block master_content %}
    <div class="table_area">
        {% csrf_token %}
        <table class="table table-hover">
            <thead>
            <tr>
                <th>作者编号</th>
                <th>姓名</th>
                <th>年龄</th>
                <th>邮箱</th>
                <th>手机号码</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
            {% for author_obj in author_list %}
                <tr>
                    <td>{{ forloop.counter }}</td>
                    <td>{{ author_obj.name }}</td>
                    <td>{{ author_obj.age }}</td>
                    <td>{{ author_obj.ad.email }}</td>
                    <td>{{ author_obj.ad.tel_phone }}</td>
                    <td>
                        <a href="{% url 'author_edit' author_obj.pk %}" class="btn btn-warning btn-xs ">编辑</a>
                        <!-- 删除我们应该使用ajax进行局部刷新,不应该和编辑一样使用页面刷新 -->
                        <a id="del_author" class="btn btn-danger btn-xs" author_id={{ author_obj.pk }}>删除</a>
                    </td>
                </tr>
                {% if forloop.last and forloop.counter > 0 %}
                    <tr>
                        <td colspan="7">
                            <a type="button" class="btn btn-info form-control add_btn" data-toggle="modal"
                               data-target="#exampleModal"
                               data-whatever="@mdo">添加作者
                            </a>

                            <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog"
                                 aria-labelledby="exampleModalLabel">
                                <div class="modal-dialog" role="document">
                                    <div class="modal-content">
                                        <div class="modal-header">
                                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                                <span aria-hidden="true">&times;</span></button>
                                            <h4 class="modal-title" id="exampleModalLabel" >作者信息添加表</h4>
                                        </div>
                                        <div class="modal-body">
                                            <form action="{% url 'author_add' %}" method="post">
                                                {% csrf_token %}
                                                <div class="form-group">
                                                    <label for="recipient-name" class="control-label">姓名</label>
                                                    <input type="text" class="form-control" id="recipient-name" name="name">
                                                </div>
                                                <div class="form-group">
                                                    <label for="recipient-name" class="control-label">年龄</label>
                                                    <input type="text" class="form-control" id="recipient-name" onkeyup="value=value.replace(/[^\d]/g,'')" maxlength="3" name="age">
                                                </div>
                                                <div class="form-group">
                                                    <label for="recipient-name" class="control-label">邮箱</label>
                                                    <input type="email" class="form-control" id="recipient-name" name="email">
                                                </div>
                                                <div class="form-group">
                                                    <label for="recipient-name" class="control-label">手机号码</label>
                                                    <input type="text" class="form-control" id="recipient-name" onkeyup="value=value.replace(/[^\d]/g,'')" maxlength="11" name="tel_number">
                                                </div>
                                                <div class="modal-footer">
                                                    <button type="submit" class="btn btn-primary">提交</button>
                                                </div>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </td>
                    </tr>
                {% endif %}
            {% endfor %}
            </tbody>
        </table>
    </div>
{% endblock %}

{% block script_area %}
    <script>
        $(function () {
            $("tbody").on('click', '#del_author', function () {
                let $ele = $(this).parent().parent()
                $.ajax({
                    url: `/author/del/${$(this).attr('author_id')}/`,
                    type: "post",
                    data: {
                        csrfmiddlewaretoken: $("input[name='csrfmiddlewaretoken']").val()
                    },
                    success: function (response) {
                        response = JSON.parse(response)
                        if (response["status"] == true) {
                            $ele.remove()
                        } else {
                            alert('作者删除失败!请重试')
                        }
                    }
                })
            })
        })
    </script>
{% endblock %}
【2】author_edit.html

这个不能采用模态框的方式显示,因为它需要渲染模板语法到页面!

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>作者管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .form-area {
            width: 600px;
            position: absolute;
            top: 130px;
            left: 300px;
        }

        h3 {
            position: relative;
            left: 270px;
            margin-bottom: 20px;
            font-family: "Kaiti SC";
            font-weight: bold;
        }

        .center-block {
            position: relative;
            left: 50px;
        }

    </style>
</head>
<body>
<div class="form-area">
    <h3>作者信息编辑表</h3>
    <form class="form-horizontal" action="{% url 'author_edit' author_obj.pk %}" method="post">
        {% csrf_token %}
        <div class="form-group">
            <label for="input_name" class="col-sm-2 control-label">姓名</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" id="input_name"  value="{{ author_obj.name }}" name="name">
            </div>
        </div>
        <div class="form-group">
            <label for="input_age" class="col-sm-2 control-label">年龄</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" id="input_age"  value="{{ author_obj.age }}" onkeyup="value=value.replace(/[^\d]/g,'')" maxlength="3" name="age">
            </div>
        </div>
        <div class="form-group">
            <label for="input_email" class="col-sm-2 control-label">邮箱</label>
            <div class="col-sm-10">
                <input type="email" class="form-control" id="input_email"  value="{{ author_obj.ad.email }}" name="email">
            </div>
        </div>
        <div class="form-group">
            <label for="input_tel_number" class="col-sm-2 control-label">手机号码</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" id="input_tel_number" value="{{ author_obj.ad.tel_phone }}" onkeyup="value=value.replace(/[^\d]/g,'')" maxlength="11" name="tel_number">
            </div>
        </div>
        <input type="submit" class="btn btn-success center-block" value="提交">
    </form>
</div>
</body>
<!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery,所以必须放在bootstrap前边) -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script>
<!-- 加载 Bootstrap 的所有 JavaScript 插件。你也可以根据需要只加载单个插件。 -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"></script>
</html>

(3)出版社管理系统相关

【1】publisher_view.html
{% extends 'index.html' %}
{% block page_title %}
    <title>出版社管理系统</title>
{% endblock %}

{% block sys_view %}
    <div class="panel-body">
        <a href="{% url 'book_view' %}">图书管理系统</a>
    </div>
    <div class="panel-body">
        <a href="{% url 'author_view' %}">作者管理系统</a>
    </div>
    <div class="panel-body active">
        <a href="{% url 'publisher_view' %}">出版社管理系统</a>
    </div>
{% endblock %}

{% block master_content %}
    <div class="table_area">
        {% csrf_token %}
        <table class="table table-hover">
            <thead>
            <tr>
                <th>出版社编号</th>
                <th>名称</th>
                <th>邮箱</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
            {% for publisher_obj in publisher_list %}
                <tr>
                    <td>{{ forloop.counter }}</td>
                    <td>{{ publisher_obj.name }}</td>
                    <td>{{ publisher_obj.email }}</td>
                    <td>
                        <!-- 删除我们应该使用ajax进行局部刷新,不应该和编辑一样使用页面刷新 -->
                        <a id="del_publisher" class="btn btn-danger btn-xs" publisher_id={{ publisher_obj.pk }}>删除</a>
                    </td>
                </tr>
                {% if forloop.last and forloop.counter > 0 %}
                    <tr>
                        <td colspan="7">
                            <a type="button" class="btn btn-info form-control add_btn" data-toggle="modal"
                               data-target="#exampleModal"
                               data-whatever="@mdo">添加出版社
                            </a>

                            <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog"
                                 aria-labelledby="exampleModalLabel">
                                <div class="modal-dialog" role="document">
                                    <div class="modal-content">
                                        <div class="modal-header">
                                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                                <span aria-hidden="true">&times;</span></button>
                                            <h4 class="modal-title" id="exampleModalLabel" >出版社信息添加表</h4>
                                        </div>
                                        <div class="modal-body">
                                            <form action="{% url 'publisher_add' %}" method="post">
                                                {% csrf_token %}
                                                <div class="form-group">
                                                    <label for="recipient-name" class="control-label">名称</label>
                                                    <input type="text" class="form-control" id="recipient-name" name="name">
                                                </div>
                                                <div class="form-group">
                                                    <label for="recipient-name" class="control-label">邮箱</label>
                                                    <input type="email" class="form-control" id="recipient-name" name="email">
                                                </div>
                                                <div class="modal-footer">
                                                    <button type="submit" class="btn btn-primary">提交</button>
                                                </div>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </td>
                    </tr>
                {% endif %}
            {% endfor %}
            </tbody>
        </table>
    </div>
{% endblock %}

{% block script_area %}
    <script>
        $(function () {
            $("tbody").on('click', '#del_publisher', function () {
                let $ele = $(this).parent().parent()
                $.ajax({
                    url: `/publisher/del/${$(this).attr('publisher_id')}/`,
                    type: "post",
                    data: {
                        csrfmiddlewaretoken: $("input[name='csrfmiddlewaretoken']").val()
                    },
                    success: function(response) {
                        response = JSON.parse(response)
                        if (response["status"] == true) {
                            $ele.remove()
                        } else {
                            alert('出版社删除失败!请重试')
                        }
                    }
                })
            })
        })
    </script>
{% endblock %}

四、项目心得总结

1、input框对手机号、年龄、email的输入限制方法

<input type="email">  # 提交表单时,如果没有@就会报错!
<input type="text" onkeyup="value=value.replace(/[^\d]/g,'')" maxlength="3" name="age">

onkeyup="" # 保证用户输入的只能是数字
maxlength="3" # 保证用户输入数字的长度,最多是三位数。手机号maxlength="11"即可

你可能感兴趣的:(#,框架,#,项目实战,django)