16 简单的图书管理系统

models.py

from django.db import models


# Create your models here.
class Book(models.Model):
   title = models.CharField(max_length=32)
   price = models.DecimalField(max_digits=8, decimal_places=2)
   publish_time = models.DateField(auto_now_add=True)
   publish = models.ForeignKey(to='Publish')
   authors = models.ManyToManyField(to='Author')

   def __str__(self):
       return '对象:%s' % self.title


class Publish(models.Model):
   name = models.CharField(max_length=32)
   addr = models.CharField(max_length=64)

   def __str__(self):
       return '对象:%s' % self.name


class Author(models.Model):
   name = models.CharField(max_length=32)
   age = models.IntegerField()
   author_detail = models.OneToOneField(to='AuthorDetail')

   def __str__(self):
       return '对象:%s' % self.name


class AuthorDetail(models.Model):
   phone = models.BigIntegerField()
   addr = models.CharField(max_length=32)

   def __str__(self):
       return '对象:%s' % self.addr

urls.py

from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
   url(r'^admin/', admin.site.urls),
   # 首页
   url(r'^$', views.home, name='hm'),
   # 图书展示
   url(r'^book_list/', views.book_list, name='bl'),
   # 图书添加
   url(r'^book_add/', views.book_add, name='ba'),
   # 图书编辑
   url(r'^book_edit/(\d+)/', views.book_edit, name='be'),
   # 图书删除
   url(r'^book_delete/(?P<delete_id>\d+)/', views.book_delete, name='bd'),
   # ajax删除
   url(r'^del_book/',views.del_book)
]

views.py

from django.shortcuts import render, redirect, HttpResponse, reverse
from app01 import models

from django.db.models import Q


# Create your views here.
def home(request):
   return render(request, 'home.html')


def book_list(request):
   book_queryset = models.Book.objects.all()
   return render(request, 'book_list.html', locals())


def book_add(request):
   if request.method == 'POST':
       # 获取用户上传的图书数据
       title = request.POST.get('title')
       price = request.POST.get('price')
       publish_time = request.POST.get('publish_time')
       publish_pk = request.POST.get('publish_pk')
       authors_pk_list = request.POST.getlist('authors_pk_list')
       '''涉及到数据的校验 暂时都不考虑 后面有现成的组件可以完成'''
       book_obj = models.Book.objects.create(title=title, price=price, publish_time=publish_time,
                                             publish_id=publish_pk)
       book_obj.authors.add(*authors_pk_list)  # getlist获取到的是列表 而add方法只能传多个参数逗号隔开 所以使用*打散
       # _url = reverse('bl')
       return redirect('bl')
       """
      redirect括号内支持直接写别名 能够自动反向解析
          但是该功能也仅仅局限于没有无名有名分组的情况 就需要借助有reverse方法
      """
   publish_queryset = models.Publish.objects.all()
   author_queryset = models.Author.objects.all()
   return render(request, 'book_add.html', locals())


def book_edit(request, edit_id):
   if request.is_ajax():
       return HttpResponse('123')
   # 获取用户需要编辑的数据对象
   edit_obj = models.Book.objects.filter(pk=edit_id).first()
   if request.method == 'POST':
       title = request.POST.get('title')
       price = request.POST.get('price')
       publish_time = request.POST.get('publish_time')
       publish_pk = request.POST.get('publish_pk')
       authors_pk_list = request.POST.getlist('authors_pk_list')
       models.Book.objects.filter(pk=edit_id).update(title=title, price=price, publish_time=publish_time,
                                                     publish_id=publish_pk)
       edit_obj.authors.set(authors_pk_list)
       # 也可以使用对象点属性的方式修改 之后点save()
       # edit_obj.title = title
       # edit_obj.price = price
       # ...
       # edit_obj.save()
       return redirect('bl')

   publish_queryset = models.Publish.objects.all()
   author_queryset = models.Author.objects.all()
   # 返回一个编辑页面(上面应该提前写好待编辑的数据)
   return render(request, 'book_edit.html', locals())


def book_delete(request,delete_id):
   models.Book.objects.filter(pk=delete_id).delete()
   return redirect('bl')


def del_book(request):
   # 判断当前请求是否是ajax请求
   # print(request.is_ajax())
   if request.is_ajax():
       if request.method == 'POST':
           delete_id = request.POST.get('delete_id')
           models.Book.objects.filter(pk=delete_id).delete()
           return HttpResponse("已经删了 你可以跑路了")

home.html

<body>
<nav class="navbar navbar-inverse">
 <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="#">BMS</a>
   </div>

   <!-- Collect the nav links, forms, and other content for toggling -->
   <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
     <ul class="nav navbar-nav">
       <li class="active"><a href="#">图书<span class="sr-only">(current)</span></a></li>
       <li><a href="#">作者</a></li>
       <li class="dropdown">
         <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
         <ul class="dropdown-menu">
           <li><a href="#">Action</a></li>
           <li><a href="#">Another action</a></li>
           <li><a href="#">Something else here</a></li>
           <li role="separator" class="divider"></li>
           <li><a href="#">Separated link</a></li>
           <li role="separator" class="divider"></li>
           <li><a href="#">One more separated link</a></li>
         </ul>
       </li>
     </ul>
     <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="#">Jason</a></li>
       <li class="dropdown">
         <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">更多操作 <span class="caret"></span></a>
         <ul class="dropdown-menu">
           <li><a href="#">Action</a></li>
           <li><a href="#">Another action</a></li>
           <li><a href="#">Something else here</a></li>
           <li role="separator" class="divider"></li>
           <li><a href="#">Separated link</a></li>
         </ul>
       </li>
     </ul>
   </div><!-- /.navbar-collapse -->
 </div><!-- /.container-fluid -->
</nav>
<div class="container-fluid">
   <div class="row">
       <div class="col-md-2">
           <div class="list-group">
             <a href="" class="list-group-item active">
              首页
             </a>
             <a href="{% url 'bl' %}" class="list-group-item">图书列表</a>
             <a href="#" class="list-group-item">出版社列表</a>
             <a href="#" class="list-group-item">作者列表</a>
             <a href="#" class="list-group-item">更多列表</a>
           </div>
       </div>
       <div class="col-md-10">
           <div class="panel panel-primary">
             <div class="panel-heading">
               <h3 class="panel-title">BMS</h3>
             </div>
             <div class="panel-body">
                  {% block content %}
                   <div class="jumbotron">
             <h1>亚洲最大的线上图书馆!</h1>
             <p>FBI warning 啥都有!!!</p>
             <p><a class="btn btn-primary btn-lg" href="#" role="button">赶紧带我去</a></p>
           </div>
                  {% endblock %}

             </div>
           </div>
           
       </div>
   </div>
</div>
{% block js %}

{% endblock %}
</body>

book_liist.html

{% extends 'home.html' %}


{% block content %}
   <h2 class="text-center">图书列表</h2>
   <a href="{% url 'ba' %}" class="btn btn-success">添加书籍</a>
   <table class="table table-hover table-striped">
       <thead>
       <tr>
           <th>主键</th>
           <th>书名</th>
           <th>价格</th>
           <th>出版日期</th>
           <th>出版社</th>
           <th>作者</th>
           <th>操作</th>
       </tr>
       </thead>
       <tbody>
      {% for book_obj in book_queryset %}
           <tr>
               <td>{{ book_obj.pk }}</td>
               <td>{{ book_obj.title }}</td>
               <td>{{ book_obj.price }}</td>
               <td>{{ book_obj.publish_time|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.name }}
                      {% else %}
                          {{ author_obj.name }},
                      {% endif %}
                  {% endfor %}

               </td>
               <td>
                   <a href="{% url 'be' book_obj.pk %}" class="btn btn-primary btn-xs">编辑</a>
                   <a href="#" class="btn btn-danger btn-xs c1" delete_id="{{ book_obj.pk }}">删除</a>
                   <!--标签既可以有默认的属性也可以有自定义的属性-->
               </td>
           </tr>
      {% endfor %}
       </tbody>
   </table>
   <nav aria-label="Page navigation" class="text-center">
       <ul class="pagination">
           <li>
               <a href="#" aria-label="Previous">
                   <span aria-hidden="true">&laquo;</span>
               </a>
           </li>
           <li><a href="#">1</a></li>
           <li><a href="#">2</a></li>
           <li><a href="#">3</a></li>
           <li><a href="#">4</a></li>
           <li><a href="#">5</a></li>
           <li>
               <a href="#" aria-label="Next">
                   <span aria-hidden="true">&raquo;</span>
               </a>
           </li>
       </ul>
   </nav>
{% endblock %}


{% block js %}
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
   <script>
       var $btn = $('.c1');
       $btn.on('click', function () {
           var delete_id = $(this).attr('delete_id');
           var $this = $(this);
           swal({
               title: "你确定要删除吗?",
               text: "一旦删除了 后果可能很严重 准备好跑路了吗?",
               icon: "warning",
               buttons: true,
               dangerMode: true,
          })
              .then((willDelete) => {
                   if (willDelete) {
                       // 朝后端发送ajax请求
                       $.ajax({
                           // 可以向当前地址发送
                           // url:'',
                           url: '/del_book/',
                           type: 'post',
                           data: {'delete_id': delete_id},
                           success: function (args) {
                               $this.parent().parent().remove();
                               swal(args, {
                                       icon: "success",
                                  }
                              );
                          }
                      })
                  } else {
                       swal("怂比 这都不敢!");
                  }
              });
      })


   </script>
{% endblock %}

 

book_add.html

{% extends 'home.html' %}


{% block content %}
   <h2 class="text-center">图书添加</h2>
   <form action="" method="post">
       <p>书名:
           <input type="text" name="title" class="form-control">
       </p>
       <p>价格:
           <input type="text" name="price" class="form-control">
       </p>
       <p>出版日期:
           <input type="date" name="publish_time" class="form-control">
       </p>
       <p>出版社:
           <select name="publish_pk" id="" class="form-control">
              {% for publish_obj in publish_queryset %}
                   <option value="{{ publish_obj.pk }}">{{ publish_obj.name }}</option>
              {% endfor %}
           </select>
       </p>
       <p>作者:
           <select name="authors_pk_list" id="" multiple class="form-control">
              {% for author_obj in author_queryset %}
                   <option value="{{ author_obj.pk }}">{{ author_obj.name }}</option>
              {% endfor %}
           </select>
       </p>
       <input type="submit" value="添加书籍" class="btn btn-success btn-block">
   </form>
{% endblock %}

book_edit.html

{% extends 'home.html' %}


{% block content %}
   <h2 class="text-center">图书编辑</h2>
   <form action="" method="post">
       <p>书名:
           <input type="text" name="title" class="form-control" value="{{ edit_obj.title }}">
       </p>
       <p>价格:
           <input type="text" name="price" class="form-control" value="{{ edit_obj.price }}">
       </p>
       <p>出版日期:
           <input type="date" name="publish_time" class="form-control" value="{{ edit_obj.publish_time|date:'Y-m-d' }}">
       </p>
       <p>出版社:
           <select name="publish_pk" id="" class="form-control">
              {% for publish_obj in publish_queryset %}
                   <!--循环所有的出版社对象 跟书籍对象的出版社比对 如果一致则添加上selected默认选项-->
                  {% if edit_obj.publish == publish_obj %}
                       <option value="{{ publish_obj.pk }}" selected>{{ publish_obj.name }}</option>
                  {% else %}
                       <option value="{{ publish_obj.pk }}">{{ publish_obj.name }}</option>
                  {% endif %}

              {% endfor %}
           </select>
       </p>
       <p>作者:
           <select name="authors_pk_list" id="" multiple class="form-control">
              {% for author_obj in author_queryset %}
                  {% if author_obj in edit_obj.authors.all %}
                       <option value="{{ author_obj.pk }}" selected>{{ author_obj.name }}</option>
                  {% else %}
                       <option value="{{ author_obj.pk }}">{{ author_obj.name }}</option>
                  {% endif %}
              {% endfor %}
           </select>
       </p>
       <input type="submit" value="编辑书籍" class="btn btn-warning btn-block">
   </form>
{% endblock %}

###

 

posted @ 2022-04-15 16:37  vonmo  阅读(16)  评论(0编辑  收藏  举报