django--BMS

  图书管理系统

 

1.创建模型

  实例: 作者模型:一个作者有姓名和年龄。

     作者详细信息模型:把作者的详情放到详情表,包含生日,手机号,家庭住址等,作者详细信息模型和作者模型是一对一的关系(OneToOne)。

     出版商模型: 出版商有名称,所在城市以及email。

       书籍模型:书籍模型有书名,价格,出版日期,出版社,作者。一本书可以会有多个作者,一个作者也可以写多本书,所以作者和书籍的关系应该是多对多的(ManyToMany),一本书只应该由一个出版商出版,所以出版社和书籍的关系应该是一对多的关系(OneToMany)。# 在models.py中创建这些表信息

from django.db import models

# create your models here.

class Author(models.Model):
    nid = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32)
    age = models.IntegerField()
    # 与AuthorDetail表创建一对一的关系
    authorDetail = models.OneToOneField(to='AuthorDetail',on_delete=models.CASCADE)
   def __str__(self):
     return self.name
class AuthorDetail(models.Model): nid = models.AutoField(pimary_key=True) tel = models.BigIntegerField() addr = models.CharField(max_length=64)
   def __str__(self):
     return self.addr  
class Publish(models.Model): nid = AutoField(primary_key=True) name = models.CharField(max_length=32) city = models.CharField(max_length=32) email = models.EmailField()
   def __str__(self):
     return self.name
class Book(models.Model): nid = models.AutoField(primary_key=True) title = models.CharField(max_length=32)
price = models.IntegerFeild()
    pub_date = models.DateTimeField()
  # 与Publish建立一对多的关系,外键字段建立在多的一方
    publish = models.ForeignKey(to='Publish',on_delete=models.CASCADE)
    # 与Author建立多对多的关系,ManyToManyField可以建立在两个表模型中的任意一个,自动会创建第三张关系表
    authors = models.ManyToManyField(to='Author',)
   def __str__(self):
     return self.title

 

2. 在项目中的__init__.py文件中导入pymysql

# 如果没有就要下载pymysql
# pip3 install pymysql

import pymysql
pymysql.install_as_MySQLdb()

      在class的每个表信息下面加上 def __str__(self): return slef.xxx

 

3.在项目中的setting.py中设置与数据库相关数据库操作的内容。

DATABASES = {
      'default':{
          'ENGINE': 'django.db.backends.mysql',
          'NAME': 'bms', # 数据库的名字
           'USER': 'root', # 数据库的用户名
           'PASSWORD': '', # 数据库的用户密码
           'PORT':3306, # 端口号
            'HOST''127.0.0.1',
    }  
}    

 

4.进行数据库迁移,在命令行中输入python manage.py makemigrations  python manage.py migrate

d:> python manage.py makemigrations
d:> python manage.py migrate

5.在url里进行配置

from django.contrib import admin
form django.urls import path,re_path,include
# 比如你创建的应用名为app01
import app1 import views # 进行导入

urlpatterns = [
    path ('admin/',admin.site.urls),
    ###图书管理系统####
    re_path('books/',views.book_view), # 主页面
    re_path('^$',views.book_view), # 根目录
    path('books/add/',views.book_add),# 添加数据页面
    re_path('^books/edit/(?P<edit_book_id>\d+)$',views.book_edit), # 修改数据页面
    re_path('^books/delete/(?P<del_book_id>\d+)$',views.book_del) , # 删除数据                 
]

6. 进入views视图函数

from django.shortcuts import render,redirect,HttpResponse

from app01.models import Book,Publish,Author,AuthorDetail

def book_view(request):
    # 主页面视图
    book_list = Book.object.all()
    return render(request,'book_view.html',{'book_list':book_list})

def book_add(request):
    # 添加
    if request.method=='GET':
        publish_list = Publist.objects.all()
        author_list = Author.objects.all()
        return render(request,'book_add.html',{'publish_list':publish_list,'author_list':author_list})
    else:
        title = request.POST.get('title')
        price = request.POST.get('price')
        pub_date = request.POST.get('pub_date')
        publish_id = request.POST.get('publish_id')
        authors = request.POST.get('authors')
        book = Book.objects.create(title=title,price=price,pub_date=pub_date,publish_id=publish_id)
        book.authors.add(*authors)
        return redirect('/books/')

def book_eidt(request,edit_book_id):
    edit_book = Book.objects.filter(pk=edit_book_id).first()
    if request.method=='GET':
        publish_list = Publish.objects.all()
        author_list = Author.objects.all()
        return render(request,'book_edit.html',{'publish_list':publish_list,'author_list':author_list})
    else:
       title = request.POST.get('title') 
       price = request.POST.get('price')
       pub_date = request.POST.get('pub_date')
       publish_id = request.POST.get('publish_id')
       authors = request.POST.get('authors') 
           
Book.objects.filter(pk=edit_book_id).update(title=title,price=price,pub_date=pub_date,publish_id=publish_id)
        edit_book.authors.set(authors)
        return redirect('/books/')

def book_del(request,del_book_id):
    Book.objects.filter(pk=del_book_id).delete()
    return redirect('/books/')
View Code

7.进入templates下创建对应的html文

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
          integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <style>
        .container{
            margin-top: 35px;
        }

    </style>
</head>
<body>
<h3>查看书籍</h3>
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <a href="/books/add/" class="btn btn-primary">添加书籍</a>
            <table class="table table-bordered 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 in book_list %}
                       <tr>
                            <td>{{ forloop.counter }}</td>
                            <td>{{ book.title }}</td>
                            <td>{{ book.price }}</td>
                            <td>{{ book.pub_date|date:'Y-m-d' }}</td>
                            <td>{{ book.publish.name }}</td>
                            <td>
                                {% for author in book.authors.all %}
                                    <span>{{ author.name }}</span>
                                    {% if not forloop.last %}
                                    ,
                                    {% endif %}
                                {% endfor %}
                            </td>
                            <td>
                                <a href="/books/edit/{{ book.pk }}" class="btn btn-danger btn-sm">编辑</a>
                                <a href="/books/delete/{{ book.pk }}" class="btn btn-warning btn-sm">删除</a>
                            </td>
                       </tr>

                   {% endfor %}

                </tbody>
            </table>
        </div>
    </div>
</div>

</body>
</html>
book_view
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
          integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

</head>
<body>
<h3>添加书籍</h3>
<div class="container">
    <div class="row">
        <div class="col-md-6 col-md-offset-3">
            <form action="" method="post">
                {% csrf_token %}
                <div class="form-group">
                    <label for="title">书籍名称</label>
                    <input class="form-control" type="text" name="title" id="title">
                </div>
                <div class="form-group">
                    <label for="price">价格</label>
                    <input class="form-control" type="text" name="price" id="price">
                </div>
                <div class="form-group">
                    <label for="pub_date">出版日期</label>
                    <input class="form-control" type="date" name="pub_date" id="pub_date">
                </div>
                <div class="form-group">
                    <label for="form-control">出版社</label>
                    <select name="publish_id" id="" class="form-control">
                        {% for publish in publish_list %}
                            <option value="{{ publish.pk }}">{{ publish.name }}</option>
                        {% endfor %}
                    </select>
                </div>
                <div class="form-group">
                    <label for="authors">作者</label>
                    <select name="authors" id="" class="form-control">
                        {% for author in author_list %}
                            <option value="{{ author.pk }}">{{ author.name }}</option>
                        {% endfor %}
                    </select>
                </div>
                <input type="submit" value="提交" class="btn btn-default pull-right">
            </form>
        </div>
    </div>
</div>
</body>
</html>
book_edit
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
          integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

</head>
<body>
<h3>编辑书籍</h3>
<div class="container">
    <div class="row">
        <div class="col-md-6 col-md-offset-2">
            <form action="" method="post">
                {% csrf_token %}
                <div class="form-group">
                    <label for="title">书籍名称</label>
                    <input class="form-control" value="{{ edit_book.title }}" type="text" name="title" id="title">
                </div>
                <div class="form-group">
                    <label for="price">价格</label>
                    <input class="form-control" value="{{ edit_book.price }}" type="text" name="price" id="price">
                </div>
                <div class="form-group">
                    <label for="pub_date">出版日期</label>
                    <input class="form-control" value="{{ edit_book.pubdate|date:'Y-m-d' }}" type="date" name="pub_date" id="pub_date">
                </div>
                <div class="form-group">
                    <label for="publish">出版社</label>
                    <select name="publish_id" id="" class="form-control">
                    {% for publish in publish_list %}
                        {% if edit_book.publish == publish %}
                            <option selected value="{{ publish.pk }}">{{ publish.name }}</option>
                        {% else %}
                            <option value="{{ publish.pk }}">{{ publish.name }}</option>
                        {% endif %}
                    {% endfor %}
                    </select>
                </div>
                <div class="form-group">
                    <label for="authors">作者</label>
                    <select name="authors" id="" class="form-control ">
                        {% for author in author_list %}
                            {% if author in edit_book.author.all %}
                                <option selected value="{{ author.pk }}">{{ author.name }}</option>
                             {% else %}
                                <option value="{{ author.pk }}">{{ author.name }}</option>
                            {% endif %}
                        {% endfor %}
                    </select>
                </div>
                <input type="submit" value="提交" class="btn btn-default pull-right">
            </form>
        </div>
    </div>
</div>
</body>
</html>
book_edit

8. 执行django项目就可以啦。

 

 

 

 
posted @ 2018-10-26 20:47  吧啦吧啦吧啦  阅读(87)  评论(0编辑  收藏  举报