博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

django之图书管理系统

Posted on 2023-06-24 14:27  乱了啦  阅读(189)  评论(0编辑  收藏  举报

后端

路由

 

urlpatterns = [
    path('admin/', admin.site.urls),
    首页
    re_path('^$', views.Bms.as_view()),
  图书 path('book/', views.Books.as_view()),
  出版社 path('publish/', views.Publish.as_view()),
  作者 path('author/', views.Authors.as_view()),
  修改 re_path('^book_update/(\d+)$', views.Update.as_view(), name="obj1"),
  删除 re_path('^book_delete/(\d+)$', views.Delete.as_view(), name="obj2"),
  添加 path('add/', views.BookAdd.as_view()), ]

 

  

 

模型层

 

# 图书表
class Book(models.Model):
    title = models.CharField(max_length=32)
    price = models.DecimalField(max_digits=8, decimal_places=2)  # 总共8位,小数点占8位
    date = models.DateField(auto_now_add=True)
    """
    图书和出版社是一对多 并且书是多的一方 所以外键字段放在书表里面
    """
    publish = models.ForeignKey(to='Publish', on_delete=models.CASCADE, )  # 默认会跟出版社表的主键关联
    """
    如果字段对应的是ForeignKey 那么会orm会自动在字段的后面加_id
    """
    authors = models.ManyToManyField(to='Author')
    """
    authors是一个虚拟字段 主要是用来告诉orm 书籍表和作者表是多对多关系
    让orm自动帮你创建第三张关系表
    """


# 出版社表
class Publish(models.Model):
    name = models.CharField(max_length=32)
    addr = models.CharField(max_length=32, null=True)
    email = models.EmailField()


# 作者表
class Author(models.Model):
    name = models.CharField(max_length=32)
    age = models.IntegerField(null=True)
    author_detail = models.OneToOneField(to='AuthorDetail', on_delete=models.CASCADE, )


# 作责详情表
class AuthorDetail(models.Model):
    phone = models.BigIntegerField()  # 或者直接字符类型
    addr = models.CharField(max_length=32)

 

  

 

视图层

 

from django.shortcuts import render, HttpResponse, redirect

# Create your views here.
from django.views import View

from app01 import models


class Bms(View):
    def get(self,request):
        return render(request, "bms.html")


class Books(View):
    def get(self,request):
        # 先查询出所有的书籍信息 传递给html页面
        book_all = models.Book.objects.all()
        return render(request, "books.html",locals())


class Publish(View):
    def get(self,request):
        return render(request, "publishs.html")


class Authors(View):
    def get(self,request):
        return render(request, "authors.html")


class BookAdd(View):
    def get(self,request):
        publish_all = models.Publish.objects.all()
        author_all = models.Author.objects.all()
        return render(request, "add.html",locals())

    def post(self,request):
        # 获取前端提交过来的所有数据
        title = request.POST.get("title")
        price = request.POST.get("price")
        publish_date = request.POST.get("date")
        publish_id = request.POST.get("publish")
        authors_list = request.POST.getlist("author")
        # 操作数据库存储数据
        # 书籍表
        book_obj = models.Book.objects.create(title=title, price=price, date=publish_date,
                                              publish_id=publish_id)
        # 书籍表与作者表的关系
        book_obj.authors.add(*authors_list)
        return redirect('/book/')


class Update(View):
    def get(self,request,up):
        edit_obj = models.Book.objects.filter(pk=up).first()
        publish_list = models.Publish.objects.all()
        author_list = models.Author.objects.all()
        return render(request, "book_up.html",locals())

    def post(self,request,up):
        # 获取当前用户想要编辑的书籍对象 展示给用户看
        edit_obj = models.Book.objects.filter(pk=up).first()
        title = request.POST.get("title")
        price = request.POST.get("price")
        publish_date = request.POST.get("date")
        publish_id = request.POST.get("publish")
        authors_list = request.POST.getlist("author")  # [1,2,3,4,]
        models.Book.objects.filter(pk=up).update(title=title,
                                                      price=price,
                                                      date=publish_date,
                                                      publish_id=publish_id
                                                      )
        # 该第三张关系表
        edit_obj.authors.set(authors_list)
        return redirect('/book/')


class Delete(View):
    def get(self, request, up):
        models.Book.objects.filter(pk=up).delete()
        return redirect("/book/")

 

  

 

前端

图书(books)

{% extends "bms.html" %}
{% block content %}
<div class="panel panel-info">
          <!-- Default panel contents -->
          <div class="panel-heading">图书<a href="/add/" class="btn btn-success btn-sm navbar-right" role="button">添加</a>
</div>
          <div class="panel-body">
                             <!-- Table -->
          <table class="table table-hover">
            <thead>
            <tr>
                <td>书名</td>
                <td>价格</td>
                <td>出版社</td>
                <td>出版日期</td>
                <td>作者</td>
                <td>操作</td>
            </tr>
            </thead>
              <tbody>
              {% for book in book_all %}
              <tr>
                <td>{{ book.title }}</td>
                <td>{{ book.price }}</td>
                <td>{{ book.publish.name }}</td>
                <td>{{ book.date|date:"Y-m-d" }}</td>
                <td>
                    {% for author in book.authors.all %}
                        {% if forloop.last %}
                            {{ author.name }}
                        {% else %}
                            {{ author.name }} |
                        {% endif %}
                    {% endfor %}

                </td>
                <td>
                    <a href="{% url "obj1" book.id %}" class="btn btn-primary">编辑</a>
                    <a href="{% url "obj2" book.id %}" class="btn btn-success">删除</a>
                </td>
              </tr>
              {% endfor %}
              </tbody>
          </table>
          </div>
        </div>
{% endblock %}

  

首页(bms)

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="{% static "bootstrap-3.4.1-dist/bootstrap-3.4.1-dist/css/bootstrap.min.css" %}">
    <script href="{% static "bootstrap-3.4.1-dist/bootstrap-3.4.1-dist/js/bootstrap.min.js" %}"></script>
</head>
<body>
<nav class="navbar navbar-default">
  <div class="container-fluid">
    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="#">图书管理系统</a>
    </div>

    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">

      <form class="navbar-form navbar-left">
        <div class="form-group">
          <input type="text" class="form-control" placeholder="Search">
        </div>
        <button type="submit" class="btn btn-default">Submit</button>
      </form>
      <ul class="nav navbar-nav navbar-right">
        <li><a href="/lon1/" class="active">登录</a></li>
        <li><a href="/regin/" class="active">注册</a></li>
      </ul>
    </div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->
</nav>
<div class="container-fluid">
    <div class="row">
        <div class="col-md-3">
            <div class="list-group">
                  <a href="" class="list-group-item active">
                    首页
                  </a>
                  <a href="/book/" class="list-group-item">图书列表</a>
                  <a href="/author/" class="list-group-item">作者列表</a>
                  <a href="/publish/" class="list-group-item">出版社列表</a>
            </div>
        </div>
        <div class="col-md-9">
            {% block content %}
                <div class="panel panel-primary">
                  <div class="panel-heading">
                    <h3 class="panel-title">首页</h3>
                  </div>
                  <div class="panel-body">
                    <div class="row">
              <div class="col-sm-6 col-md-4">
                <div class="thumbnail">
                  <img src="../static/imge/1.jpg" alt="...">
                  <div class="caption">
                    <h3>图书</h3>
                    <p><a href="/book/" class="btn btn-primary" role="button">Button</a></p>
                  </div>
                </div>

              </div>
              <div class="col-sm-6 col-md-4">
                <div class="thumbnail">
                  <img src="../static/imge/2.jpg" alt="...">
                  <div class="caption">
                    <h3>作者</h3>
                    <p><a href="/author/" class="btn btn-primary" role="button">Button</a></p>
                  </div>
                </div>

            </div>
              <div class="col-sm-6 col-md-4">
                <div class="thumbnail">
                  <img src="../static/imge/3.jpg" alt="...">
                  <div class="caption">
                    <h3>出版社</h3>
                    <p><a href="/publish/" class="btn btn-primary" role="button">Button</a></p>
                  </div>
                </div>

            </div>
              <div class="col-sm-6 col-md-4">
                <div class="thumbnail">
                  <img src="../static/imge/4.jpg" alt="...">
                  <div class="caption">
                    <h3>废物一个</h3>
                    <p><a href="/bao/" class="btn btn-primary" role="button">查看特性</a></p>
                  </div>
                </div>
            </div>
            </div>
                  </div>
                </div>
            {% endblock %}
{#        模板的导入#}
{#        {% include "file.html" %}#}
        </div>
    </div>
</div>
</body>
</html>

  

编辑

{% extends "bms.html" %}
{% block content %}
    <div class="container">
    <div class="row">
        <div class="col-lg-8 col-md-offset-2">
            <h2 class="text-center">修改书籍</h2>
    <form method="post">
        {% csrf_token %}
        <p>书名:<input class="form-control" type="text" name="title" value="{{ edit_obj.title }}"><p/>
        <p>价格:<input class="form-control" type="text" name="price" value="{{ edit_obj.price }}"><p/>
        <p>日期:<input class="form-control" type="date" name="date" value="{{ edit_obj.date|date:"Y-m-d" }}"><p/>
        <p>出版社:
            <select name="publish" id="" class="form-control">
                {% for obj in publish_list %}
                    {% if edit_obj.publish == obj%}
                        <option value="{{ obj.pk }}" selected>{{ obj.name }}</option>
                        {% else %}
                         <option value="{{ obj.pk }}">{{ obj.name }}</option>
                    {% endif %}
                {% endfor %}
            </select>
        <p/>
        <p>作者:
            <select name="author" id="" multiple class="form-control">
                {% for obj1 in author_list %}
                    {% if obj1 in edit_obj.authors.all %}
                        <option value="{{ obj1.pk }}" selected>{{ obj1.name }}</option>
                    {% else %}
                        <option value="{{ obj1.pk }}">{{ obj1.name }}</option>
                    {% endif %}
                {% endfor %}
            </select>
        <p/>
        <p><input class="form-control btn-success" type="submit" name="submit"><p/>
    </form>
        </div>
    </div>
</div>
{% endblock %}

  

添加

{% extends "bms.html" %}
{% block content %}
    <div class="container">
    <div class="row">
        <div class="col-lg-8 col-md-offset-2">
            <h2 class="text-center">修改书籍</h2>
    <form method="post">
        {% csrf_token %}
        <p>书名:<input class="form-control" type="text" name="title" value="{{ up_id.title }}"><p/>
        <p>价格:<input class="form-control" type="text" name="price" value="{{ up_id.price }}"><p/>
        <p>日期:<input class="form-control" type="date" name="date" value="{{ up_id.price }}"><p/>
        <p>出版社:
            <select name="publish" id="" class="form-control">
                {% for obj in publish_all %}
                    <option value="{{ obj.pk }}">{{ obj.name }}</option>
                {% endfor %}
            </select>
        <p/>
        <p>作者:
            <select name="author" id="" multiple class="form-control">
                {% for obj1 in author_all %}
                    <option value="{{ obj1.pk }}">{{ obj1.name }}</option>
                {% endfor %}
            </select>
        <p/>
        <p><input class="form-control btn-success" type="submit" name="submit"><p/>
    </form>
        </div>
    </div>
</div>
{% endblock %}

  settings

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'bms',
        'USER': 'root',
        'PASSWORD': '',
        'HOST': '127.0.0.1',
        'PORT': 3306,
    }
}

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'app01/static')
]