• 图书管理系统增删改查


    描述: 图书管理系统简单实现增删改查,实例如下

                   

    1.  框架整体目录结构

                               

           (1)建立templates,存放html文件

      (2)建立statics目录结构,存放js,css,plugins等

      (3)配置booksys/urls.py

    import pymysql
    pymysql.install_as_MySQLdb()
    

      

    2. 连接数据库配置,模块目录,静态文件等配置

      主要配置标红的地方

    import os
    DEBUG = True
    ALLOWED_HOSTS = []
    # Application definition
    
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'app1.apps.App1Config',
    ]
    
    MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        # 'django.middleware.csrf.CsrfViewMiddleware',      #先注释
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ]
    
    ROOT_URLCONF = 'booksys.urls'
    
    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [os.path.join(BASE_DIR, "templates")],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
            },
        },
    ]
    
    WSGI_APPLICATION = 'booksys.wsgi.application'
    
    
    # Database
    # https://docs.djangoproject.com/en/2.2/ref/settings/#databases
    
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
            'NAME':'booksys',
            'USER': 'root',  # 连接数据库的用户名
            'PASSWORD': 'REDHAT',  # 连接数据库的密码
            'HOST': '127.0.0.1',  # IP地址
            'POST': 3306,  # 端口号
        }
    }
    
    
    # Password validation
    # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
    
    AUTH_PASSWORD_VALIDATORS = [
        {
            'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
        },
    ]
    
    LANGUAGE_CODE = 'en-us'
    TIME_ZONE = 'UTC'
    USE_I18N = True
    USE_L10N = True
    USE_TZ = True
    
    
    # Static files (CSS, JavaScript, Images)
    # https://docs.djangoproject.com/en/2.2/howto/static-files/
    
    STATIC_URL = '/static/'
    STATICFILES_DIRS = [
        os.path.join(BASE_DIR, "statics")
    ]

    3. model文件迁移

    from django.db import models
    # Create your models here.
    class Book(models.Model):
    	title = models.CharField(max_length=32)
    	price = models.DecimalField(max_digits=9, decimal_places=2)
    	pub_date = models.DateField()
    	# 收藏数 临时加字段,设置默认值,防止为空报错行为
    	keepnum = models.IntegerField(default=100)
    	# 点赞数 临时加字段,设置默认值,防止为空报错行为
    	zannum = models.IntegerField(default=101)
    
    	# ForeignKey会生成字段publisher_id实现一对多
    	publisher = models.ForeignKey("Publish", on_delete=models.CASCADE)
    
    	# ManyToManyField会创建第三张表Book_authors实现多对多的关系
    	authors = models.ManyToManyField("Author")
    
    class Publish(models.Model):
    	name = models.CharField(max_length=32)
    	addr = models.CharField(max_length=32)
    	email = models.CharField(max_length=32)
    
    	# 打印对象返回的是出版社的名字
    	def __str__(self):
    		return self.name
    
    
    class Author(models.Model):
    	# books = models.ManyToManyField("Book")
    	name = models.CharField(max_length=32)
    	tel = models.CharField(max_length=32)
    	# OneToOneField会创建一个唯一约束字段ad_id字段实现一对一关系
    	ad = models.OneToOneField("AuthorDetail", on_delete=models.CASCADE)
    
    
    class AuthorDetail(models.Model):
    	addr = models.CharField(max_length=32)
    	gf = models.CharField(max_length=32)
    

      【modes迁移及数据库配置】

    ## python manage.py makemigrations
    ## python manage.py migrate
    

      

      【查询生成的表结构】:迁移完成查看数据库表结构,数据库数据自行录入

             

    4. 建立增删改查html文件

        HTML文件先提前写好,下面有相关html原代码:

                

      【add.html】

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
        <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-8 col-md-offset-2">
                <form action="/book/add/" method="post">
    			
                    <div class="form-group">
                        <label for="title">书籍名称</label>
                        <input type="text" class="form-control" id="title" placeholder="title" name="title">
                    </div>
    				
                    <div class="form-group">
                        <label for="price">价格</label>
                        <input type="text" class="form-control" id="price" placeholder="price" name="price">
                    </div>
    				
                    <div class="form-group">
                        <label for="date">出版日期</label>
                        <input type="date" class="form-control" id="date" placeholder="date" name="pub_date">
                    </div>
    
    
                    <div class="form-group">
                         <label for="publisher">出版社</label>
    					 <!-- 单选下拉框 -->
                        <select name="publisher_id" id="publisher" 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>
    					<!-- multiple 多选下拉框 -->
                        <select name="author_ids" id="authors" class="form-control" multiple>
                            {% for author in author_list %}
                            <option value="{{ author.pk }}">{{ author.name }}</option>
                            {% endfor %}
                        </select>
                    </div>
    
    
                    <input type="submit" class="btn btn-success pull-right" value="提交数据1" />
                </form>
            </div>
        </div>
    </div>
    
    
    
    </body>
    </html>
    

     【delete.html】

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <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-8 col-md-offset-2">
                 <table class="table table-striped">
    
                    <tbody>
    
                        <tr>
    
                            <td>{{ data.title }}</td>
                            <td>{{ data.price }}</td>
                            <td>{{ data.pub_date|date:"Y-m-d" }}</td>
                            <td>{{ data.publisher.name }}</td>
                            <td>
                                {% for author in data.authors.all %}
                                <span class="btn-sm btn-success">{{ author.name }}</span>
                                {% endfor %}
                            </td>
    
                        </tr>
    
    
                    </tbody>
                </table>
                <form action="/book/delete/{{ data.pk }}/" method="post">
                    <button class="btn-danger">确认删除?</button>
                </form>
    
            </div>
        </div>
    </div>
    
    </body>
    </html>
    

      【edit.html】

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
        <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-8 col-md-offset-2">
                <form action="/book/edit/{{ data.pk }}/" method="post">
    				<div class="form-group">
    					<label for="title">书籍名称</label>
    				<input type="text" class="form-control" id="title" placeholder="title" name="title" value="{{ data.title }}">
    				</div>
    				<div class="form-group">
    					<label for="price">价格</label>
    					<input type="text" class="form-control" id="price" placeholder="price" name="price" value="{{ data.price }}">
    				</div>
    				<div class="form-group">
    					<label for="date">出版日期</label>
    					<input type="date" class="form-control" id="date" placeholder="date" name="pub_date" value="{{ data.pub_date |date:'Y-m-d'}}">
    				</div>
    
    				<div class="form-group">
    					<label for="publisher">出版社</label>
    					<select name="publisher_id" id="publisher" class="form-control">
                            {% for publish in pulish_list %}
                                {% if data.publisher == publish %}
    						    <option value="{{ publish.pk }}"  selected>{{ 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="author_ids" id="authors" class="form-control" multiple>
                            {% for author in author_list %}
                                {% if author in author_list %}
    						        <option value="{{ author.pk }}" selected>{{ author.name }}</option>
                                    {% else %}
    						        <option value="{{ author.pk }}">{{ author.name }}</option>
                                {% endif %}
                            {% endfor %}
    					</select>
    				</div>
    				<button type="submit" class="btn btn-success pull-right">提交数据</button>
                </form>
            </div>
        </div>
    </div>
    
    
    
    </body>
    </html>
    

      【index.html】首页

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
         <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
        <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-8 col-md-offset-2">
                <a href="/book/add/" class="btn btn-primary">添加书籍</a>
                <table class="table table-striped">
                    <thead>
                      <tr>
                          <th>序号</th>
                          <th>书籍名称</th>
                          <th>价格</th>
                          <th>出版日期</th>
                          <th>出版社</th>
                          <th>作者</th>
                          <th>操作</th>
                      </tr>
                    </thead>
                    <tbody>
                        {% for data in book_list %}
                        <tr>
                            <td>{{ forloop.counter }}</td>
                            <td>{{ data.title }}</td>
                            <td>{{ data.price }}</td>
                            <td>{{ data.pub_date |date:'Y-m-d'}}</td>
                            <td>{{ data.publisher.name }}</td>
                            <td>
                                {% for author in data.authors.all %}
                                <span class="btn-sm btn-success"> {{ author.name }} </span>
                                {% endfor %}
                            </td>
                            <td>
                                <a class="btn-sm btn-warning" href="/book/edit/{{ data.pk }}">编辑</a>
                                <a class="btn-sm btn-danger" href="/book/delete/{{ data.pk }}">删除</a>
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    
    </body>
    </html>

     

    5. url 路由配置

    from django.contrib import admin
    from django.urls import path,re_path
    from app1 import views
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('book/index/',views.index),
        path('book/add/',views.add),
        # path('book/edit/',views.edit),
        re_path('book/delete/(d+)/',views.delete),
        re_path('book/edit/(d+)/',views.edit),
    ]
    

    6. views文件配置,附有增删改查

    from django.shortcuts import render,HttpResponse,redirect
    from app1.models import Book,Publish,Author,AuthorDetail
    from django.http import JsonResponse
    # Create your views here.
    def index(request):
        book_list = Book.objects.all()
        return render(request, "index.html", {"book_list": book_list})
    
    def add(request):
        if request.method == "GET":
            publish_list = Publish.objects.all()
            author_list = Author.objects.all()
            print(author_list)
            return render(request, "add.html",{"publish_list":publish_list,"author_list":author_list })
        elif request.method == "POST":
            dic = request.POST.dict()
            lst = request.POST.getlist("author_ids")
            dic.pop("author_ids")
            data = Book.objects.create(**dic)
            data.authors.add(*lst)
            res = data.authors.filter().count()
            if data.id and res:
                return redirect("/book/index/")
            else:
                return HttpResponse("添加失败")
            # return HttpResponse("add ok")
    
    def delete(request,del_id):
    	if request.method == "GET":
    		data = Book.objects.get(pk=del_id)
    		return render(request,"delete.html",{"data":data})
    	elif request.method == "POST":
    		# 查询单条数据
    		data = Book.objects.filter(id=del_id)
    		# 删除 , 返回删除的条数
    		res = data.delete()
    		print(res)
    		if res:
    			return redirect("/book/index/")
    		else:
    			return HttpResponse("删除失败了")
    
    def edit(request,edit_id):
        if request.method == "GET":
            data = Book.objects.get(pk=edit_id)
            pulish_list = Publish.objects.all()
            author_list = Author.objects.all()
            return render(request, "edit.html", locals())
        elif request.method == "POST":
            dic = request.POST.dict()
            author_ids = request.POST.getlist("author_ids")
            dic.pop("author_ids")
            data = Book.objects.filter(pk=edit_id)
            res = data.update(**dic)  # 简写
            print(res)
            # return HttpResponse("edit ok")
    
            data = Book.objects.get(pk=edit_id)
            data.authors.set(author_ids)
            res2 = data.authors.filter().count()
            if res and res2:
                return redirect("/book/index/")
            else:
                return HttpResponse("编辑失败")
    
    def index1(request):
        return render(request, "index1.html")
    
    def ajax_sum(request):
        num1 = request.POST.get("num1")
        num2 = request.POST.get("num2")
        ret = {'status': 1, "msg": None}
        # print(type(num1), num2)
    
        total = int(num1) + int(num2)
        ret['msg'] = total
    
        # return HttpResponse(total)
        return JsonResponse(ret)
    

    7. 测试程序

      【增加图书操作】

        (1)点击“添加书籍”按钮

                                 

           

         (2)出现添加书籍页面,输入相关数据即可,添加成功自动会跳转到首页

                                     

       

      【测试delete】

            (1)点击任意一个“删除按钮” ---点击777777777书籍的删除按钮

                             

             (2)进入一个删除确认按钮

                                  

             (3)删除成功会跳转到首页,此时首页查询无777777777这本书 

                           

      【编辑edit】

            (1)点击11这本书的编辑按钮

                                 

             (2)出现1名称书籍的所有编辑书籍信息

                                

             (3)修改点击提交书籍即可修改数据完成

  • 相关阅读:
    hdu4639 hehe ——斐波纳契数列,找规律
    codefoces round193a
    codeforces 192e
    abbyy cup a
    年中总结
    codeforces 192a
    codeforces 192b
    codeforces 192 c
    codeforces 192 D
    codeforces magic five --快速幂模
  • 原文地址:https://www.cnblogs.com/NGU-PX/p/14189969.html
Copyright © 2020-2023  润新知