路飞学城Python-Day100

Django项目之图书馆项目

1.项目架构

路飞学城Python-Day100_第1张图片

2.表结构设计

from django.db import models

# Create your models here.


#作者详情表
class AuthorDeatil(models.Model):
    nid = models.AutoField(primary_key=True)
    birthday = models.DateField()
    telephone = models.BigIntegerField()
    addr = models.CharField(max_length=64)


# 出版社表
class Publish(models.Model):
    nid = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32)
    city = models.CharField(max_length=32)
    email = models.EmailField()


# 书籍表
class Book(models.Model):
    nid = models.AutoField(primary_key=True)
    title = models.CharField(max_length=32)
    publishDate = models.DateField()
    price = models.DecimalField(max_digits=5, decimal_places=2)
    publish = models.ForeignKey(to="Publish", to_field="nid", on_delete=models.CASCADE)
    # 多对多关系表
    authors = models.ManyToManyField(to='Author')

    def __str__(self):
        return self.title


# 作者表
class Author(models.Model):
    nid = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32)
    age = models.IntegerField()
    authordetail = models.OneToOneField(to="AuthorDeatil", to_field="nid", on_delete=models.CASCADE)

    def __str__(self):
        return self.name
models.py

3.Settings设计

"""
Django settings for book_sys2 project.

Generated by 'django-admin startproject' using Django 2.1.2.

For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '39as(vby5vue!jq@tvs+xuaksiv7+r(964)c-xv8ysh05a9rww'

# SECURITY WARNING: don't run with debug turned on in production!
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',
    'app01.apps.App01Config',
]

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 = 'book_sys2.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 = 'book_sys2.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/2.1/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',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/

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.1/howto/static-files/

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)
settings.py

4.路由设计

"""book_sys2 URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, re_path
from app01 import views

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path('index/$', views.index),
    re_path('index/add/$', views.add_book),
    re_path('books/(\d+)/change/$', views.change_book),
    re_path('books/(\d+)/delete/$', views.delete_book),
]
urls.py

5.视图设计

from django.shortcuts import render, HttpResponse, redirect
from .models import Publish, Author, Book, AuthorDeatil
# Create your views here.


def add_book(request):
    if request.method == "POST":
        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_id_list = request.POST.getlist("authors_id_list")
        book_obj = Book.objects.create(title=title, price=price, publishDate=pub_date, publish_id=publish_id)
        book_obj.authors.add(*authors_id_list)
        return redirect("/index/")
    publish_list = Publish.objects.all()
    author_list = Author.objects.all()
    return render(request, "addbook.html", locals())


def index(request):
    book_list = Book.objects.all()
    pub_list = Publish.objects.all()
    au_list = Author.objects.all()
    au_name = []
    pu_name = []
    for n in au_list:
        au_name.append(n.name)
    for n in pub_list:
        pu_name.append(n.name)
    if request.method == "POST":
        name = request.POST.get('name')
        # print(name)
        # 根据作者拿到所有的书本
        if name in au_name:
            author_obj = Author.objects.get(name=name)
            book_list_1 = author_obj.book_set.all()
        # 根据出版社拿到所有的书本
        elif name in pu_name:
            pub_obj = Publish.objects.get(name=name)
            book_list_1 = pub_obj.book_set.all()
    return render(request, "index.html", locals())
    # return HttpResponse("OK")


def change_book(request, edit_id):
    edit_book_obj = Book.objects.filter(pk=edit_id).first()
    publish_list = Publish.objects.all()
    author_list = Author.objects.all()
    if request.method == "POST":
        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_id_list = request.POST.getlist("authors_id_list")
        Book.objects.filter(pk=edit_id).update(title=title, price=price, publishDate=pub_date,
                                                    publish_id=publish_id)
        edit_book_obj.authors.set(authors_id_list)
        return redirect("/index/")
    return render(request, "changebook.html", locals())


def delete_book(request, del_id):
    Book.objects.filter(pk=del_id).delete()
    return redirect("/index/")
views.py

6.模板设计

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>添加书籍title>
    <link rel="stylesheet" href="/static/bootstrap/dist/css/bootstrap.min.css">
    <style type="text/css">
        * {
            margin: 0;
            padding: 0;
        }
        .navbar-header {
            display: inline-block;
            width: 800px;
        }
        .ul_list {
            padding-top: 8px;
            padding-left: 15px;
            display: inline-block;
            color: #fff;
        }

        #con_btn {
            padding: 0;
        }

        .row {
            float: right;
            display: inline-block;
            width: 600px;
            padding-top: 15px;
            padding-left: 200px;
        }

        .input-group {
            width: 300px;
        }

        .container1 {
            width: 60%;
            margin: auto;
        }

        #sub-btn {
            width: 20%;
            margin: auto;
        }

        #cancel {

            display: inline-block;
            float: right;
            margin-top: -36px;
        }
    style>
head>
<body>
<div class="lead_head">
    {#导航条#}
    <nav class="navbar navbar-inverse">
        <div class="container-fluid">
            <div class="navbar-header">
                <div class="logo">
                    <div class="container">
                        <div class="ul_list">
                            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-9">
                                <ul class="nav navbar-nav">
                                    <li><a href="#" id="con_btn">
                                        <button type="button" class="btn btn-default navbar-btn">Welcome to the Book
                                            Store
                                        button>
                                    a>li>
                                    <li>
                                        <a href="#">Indexa>li>

                                    <li>
                                        <a href="#">Booksa>
                                    li>
                                    <li>
                                        <a href="#">Issuersa>li>
                                    <li>
                                        <a href="#">Authorsa>li>

                                ul>
                                li>
                                ul>
                            div>

                        div>
                    div>

                div>
            div>
            <div class="row">
                <div class="col-lg-6">
                    <div class="input-group">
                        <input type="text" class="form-control" placeholder="Anything U Want">
                        <span class="input-group-btn">
                            <button class="btn btn-default" type="button">Searchbutton>
                        span>
                    div>
                div>
            div>
        div>
    nav>
div>

<div class="container1">
    <div class="row1">

        <form action="" method="post">
            {% csrf_token %}
            <div class="form-group">
                <label for="">名称label>
                <input type="text" name="title" class="form-control" value="">
            div>

            <div class="form-group">
                <label for="">价格label>
                <input type="text" name="price" class="form-control">
            div>

            <div class="form-group">
                <label for="">出版日期label>
                <input type="date" name="pub_date" class="form-control">
            div>

            <div class="form-group">
                <label for="">出版社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="">作者label>
                <select type="text" name="authors_id_list" multiple class="form-control">
                    {% for author in author_list %}
                        <option value="{{ author.pk }}">{{ author.name }}option>
                    {% endfor %}

                select>
            div>
            <input type="submit" class="btn btn-default" id="sub-btn">
        form>
        <a id="cancel" href="/index/"><input type="submit" class="btn btn-default" value="Cancel">a>
    div>
div>
body>
html>
addbook.html
DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ChangeBooktitle>
     <link rel="stylesheet" href="/static/bootstrap/dist/css/bootstrap.min.css">
    <style type="text/css">
        * {
            margin: 0;
            padding: 0;
        }
        .navbar-header {
            display: inline-block;
            width: 800px;
        }
        .ul_list {
            padding-top: 8px;
            padding-left: 15px;
            display: inline-block;
            color: #fff;
        }

        #con_btn {
            padding: 0;
        }

        .row {
            float: right;
            display: inline-block;
            width: 600px;
            padding-top: 15px;
            padding-left: 200px;
        }

        .input-group {
            width: 300px;
        }

        .container1 {
            width: 60%;
            margin: auto;
        }
style>
head>
<body>
<div class="lead_head">
    {#导航条#}
    <nav class="navbar navbar-inverse">
        <div class="container-fluid">
            <div class="navbar-header">
                <div class="logo">
                    <div class="container">
                        <div class="ul_list">
                            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-9">
                                <ul class="nav navbar-nav">
                                    <li><a href="#" id="con_btn">
                                        <button type="button" class="btn btn-default navbar-btn">Welcome to the Book
                                            Store
                                        button>
                                    a>li>
                                    <li>
                                        <a href="#">Indexa>li>

                                    <li>
                                        <a href="#">Booksa>
                                    li>
                                    <li>
                                        <a href="#">Issuersa>li>
                                    <li>
                                        <a href="#">Authorsa>li>

                                ul>
                                li>
                                ul>
                            div>

                        div>
                    div>

                div>
            div>
            <div class="row">
                <div class="col-lg-6">
                    <div class="input-group">
                        <input type="text" class="form-control" placeholder="Anything U Want">
                        <span class="input-group-btn">
                            <button class="btn btn-default" type="button">Searchbutton>
                        span>
                    div>
                div>
            div>
        div>
    nav>
div>
<div class="container1">
    <div class="row1">
        <div class="col-md-6 col-md-offset-3">
            <form action="" method="post">
                {% csrf_token %}
                <div class="form-group">
                    <label for="">名称label>
                    <input type="text" name="title" class="form-control" value="{{ edit_book_obj.title }}">
                div>

                <div class="form-group">
                    <label for="">价格label>
                    <input type="text" name="price" class="form-control" value="{{ edit_book_obj.price }}">
                div>

                <div class="form-group">
                    <label for="">出版日期label>
                    <input type="date" name="pub_date" class="form-control"
                           value="{{ edit_book_obj.publishDate|date:'Y-m-d' }}">
                div>
                <div class="form-group">
                    <label for="">出版社label>
                    <select name="publish_id" id="" class="form-control">
                        {% for publish in publish_list %}
                            {% if edit_book_obj.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="">作者label>
                    <select type="text" name="authors_id_list" multiple class="form-control">
                        {% for author in author_list %}
                        {% if author in edit_book_obj.authors.all %}
                            <option selected value="{{ author.pk }}">{{ author.name }}option>
                        {% else %}
                             <option value="{{ author.pk }}">{{ author.name }}option>
                        {% endif %}

                        {% endfor %}
                    select>
                div>
                <input type="submit" class="btn btn-default">
            form>
        div>
    div>
div>
body>
html>
changebook.html
DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>图书管理系统V1.0title>
    <style type="text/css">
        * {
            margin: 0;
            padding: 0;
        }
        .navbar-header{
            display: inline-block;
            width: 800px;
        }
        .ul_list{
            padding-top: 8px;
            padding-left: 15px;
            display: inline-block;
            color: #fff;
        }
        #con_btn{
            padding: 0;
        }
        .row{
            float: right;
            display: inline-block;
            width: 600px;
            padding-top: 15px;
            padding-left: 200px;
        }
        .input-group{
            width: 300px;
        }
        .lead_body{
            width: 100%;
            height: 80%;
            text-align: center;
            background-color: #e5e5e5;
            margin: auto;
        }
        .inner_body{
            width: 80%;
            height: 80%;
            {#background-color: #1b6d85;#}
            margin: auto;
            {#border: 1px solid gray;#}
        }
        .td{
            text-align: center;
        }
        .ul_left{
            float: left;
            padding-left: 60px;
            list-style-type:none;
            font-size: 25px;
        }
        .ul_left .blank{
            {#height: 100px;#}
            {#width: 10px;#}
            padding-bottom: 100px;
        }
        .ul_left .click1:hover{
            cursor: pointer;
            color: orange;
        }
        .ul_left .click2:hover{
            cursor: pointer;
            color: orange;
        }
        .ul_left .click3:hover{
            cursor: pointer;
            color: orange;
        }
        .left_body{
            height: 333px;
            float: left;
            background-color: white;
            margin-left: -685px;
            display: inline-block;
            position: fixed;
            z-index: 999;
        }
        #show-books, #show-issuers, #show-authors{
            border: none;
        }
        #close{
            float: right;
            margin-right: 10px;
            cursor: pointer;
            margin-top: 10px;
            position: relative;
            z-index: 999;
            font-size: 25px;
        }


    style>
    <link rel="stylesheet" href="/static/bootstrap/dist/css/bootstrap.min.css">
head>
<body>
<div class="lead_head">
    {#导航条#}
    <nav class="navbar navbar-inverse">
        <div class="container-fluid">
            <div class="navbar-header">
                <div class="logo">
                    <div class="container">
                        <div class="ul_list">
                            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-9">
                                <ul class="nav navbar-nav">
                                    <li><a href="#" id="con_btn">
                                        <button type="button" class="btn btn-default navbar-btn">Welcome to the Book
                                            Store
                                        button>
                                    a>li>
                                    <li>
                                        <a href="#">Indexa>li>

                                    <li>
                                        <a href="#">Booksa>
                                    li>
                                    <li>
                                        <a href="#">Issuersa>li>
                                    <li>
                                        <a href="#">Authorsa>li>

                                ul>
                                li>
                                ul>
                            div>

                        div>
                    div>

                div>
            div>
            <div class="row">
                <div class="col-lg-6">
                    <div class="input-group">
                        <input type="text" class="form-control" placeholder="Anything U Want">
                        <span class="input-group-btn">
                            <button class="btn btn-default" type="button">Searchbutton>
                        span>
                    div>
                div>
            div>
        div>
    nav>
div>
    <ul class="ul_left">
        <li class="click1">Authorsli>
        <li class="blank">li>
        <li class="click2">Issuersli>
        <li class="blank">li>
        <li class="click3">Booksli>
    ul>
<div class="lead_body">
    <div class="left_body">
        <div class="author" style="display: none">
            <form action="" method="post">
                 {% csrf_token %}
                <h3>Authorsh3>
            {% for authors in au_list %}
                <button id="show-authors" type="submit"  value="{{ authors }}" name="name" class="btn btn-default btn-lg btn-block">{{ authors }}button>
                {% endfor %}
                <button id="back1" type="button" class="btn btn-default btn-lg btn-block">Hide<<>
            form>
        div>
        <div class="issuers" style="display: none">
         <h3>Issuersh3>
            <form action="" method="post">
             {% for issuers in pub_list %}
                 {% csrf_token %}
                  <button id="show-issuers" type="submit" value="{{ issuers.name }}" name="name" class="btn btn-default btn-lg btn-block">{{ issuers.name }}button>
                {% endfor %}
                <button id="back2" type="button" class="btn btn-default btn-lg btn-block">Hide<<>
        form>
        div>
    <div class="books" style="display: none">
    <h3>Booksh3>
         {% for books in book_list %}
                  <button id="show-books" type="button" class="btn btn-default btn-lg btn-block">《{{ books }}》button>
                {% endfor %}
            <button id="back3" type="button" class="btn btn-default btn-lg btn-block">Hide<<>
    div>
    div>
    <div class="inner_body">


        {#巨幕内容,其他母版引用的时候要删除#}
        <div class="jumbotron">
            <div id="first" >
            <h1>Welcome!h1>
            <p>Here is something U want to know before U begin !p>
            <p><a id="show" class="btn btn-primary btn-lg" href="#" role="button">Show Mea>p>
            <p><a id="hide" class="btn btn-default btn-lg" href="#" role="button" style="display: none">Hidea>
                <a id="add" class="btn btn-info btn-lg" href="/index/add/" role="button" style="display: none">Add Booka>
            p>
            div>
            <div id="second" >
            <span id="close" >Xspan>
                <h1>{{ name }}h1>
                {% for n in book_list_1 %}
                    <p>《{{ n }}》p>
                {% endfor %}


            div>
            div>
    <table id="show-hide" class="table table-bordered table-hover table-striped" style="display: none">
             <thead>
                    <tr>
                         <th class="td" >Numberth>
                         <th class="td">Titleth>
                         <th class="td">Priceth>
                         <th class="td">Release Dateth>
                         <th class="td">Publishing Houseth>
                         <th class="td">Authorsth>
                         <th class="td">Actionth>
                    tr>
                 thead>
           <tbody>
           {% for book in book_list %}
                <tr>
                         <td>{{ forloop.counter }}td>
                         <td >{{ book.title }}td>
                         <td >{{ book.price }}元td>
                            <td >{{ book.publishDate|date:"Y-m-d" }}td>
                         <td >{{ book.publish.name }}td>
                         <td >{% for author in book.authors.all %}
                                  {% if forloop.last %}
                                   <span>{{ author.name }}span>
                                  {% else %}
                                   <span>{{ author.name }}span>,
                                  {% endif %}
                               {% endfor %}td>
                         <td > <a href="/books/{{ book.pk }}/change/" class="btn btn-warning">Edita>
                               <a id="del" href="/books/{{ book.pk }}/delete/" class="btn btn-danger">Deletea>td>
                    tr>
           {% endfor %}
           tbody>

        table>
        div>

        div>
    div>
div>
body>
<script type="text/javascript" src ="../static/JS/jQuery_File/jquery-3.3.1.min.js">script>
<script type="text/javascript">
    $("#show").click(function () {
        $("#show, #every_list").hide();
        $("#hide, #add").show();
       $('#show-hide').fadeIn();
    });
    $("#hide").click(function () {
         $('#show-hide').fadeOut();
         $("#show, #every_list").show();
        $("#add, #hide").hide();
    });
    $('.click1').mouseover(function () {
       $('.author').show('10000');

    });

    $('.click2').mouseover(function () {
       $('.issuers').show('10000');
    });

    $('.click3').mouseover(function () {
       $('.books').show('10000');
    });
    $('#back1,#back2,#back3 ').click(function () {
       $('.books, .issuers, .author').hide('10000');
    });
    $('#close').click(function () {
       $('#close, #second').hide();
       {#$('#first').show();#}
    });
    $('#del').click(function () {
       confirm('you will delete a book!');
    });
script>

html>
index.html

 路飞学城Python-Day100_第2张图片

 

转载于:https://www.cnblogs.com/pandaboy1123/p/9760541.html

你可能感兴趣的:(路飞学城Python-Day100)