图书管理系统

from django.db import models

# Create your models here.

class Publish(models.Model):
    nid=models.AutoField(primary_key=True) #主键默认自己也会创建
    name=models.CharField(max_length=32) #CharField在数据库中就是varchar
    addr=models.CharField(max_length=64)
    email=models.EmailField()            #EmailField在数据库中也是varchar

class Author(models.Model):
    nid=models.AutoField(primary_key=True)
    name=models.CharField(max_length=32)
    age=models.IntegerField()            #在数据库中就是int类型

class Book(models.Model):
    nid=models.AutoField(primary_key=True)
    name=models.CharField(max_length=32)
    price=models.DecimalField(max_digits=5,decimal_places=2) #float,最大位数5,小数位最大2
    pub_date=models.DateField()                               #日期型
    publish=models.ForeignKey(to='Publish',to_field='nid')  #外键,在多的表中建立外键,字段名:publish_id
    authors=models.ManyToManyField(to='Author')              #新建一个表:_book_authors book_id author_id

# publish author book
# book publish 一个出版社多本书  一本书一个出版社  多对一  外键在多的里面
# book author  一本书多个作者    一个作者多本书    多对多  在那张表中都行
models
from django.shortcuts import render,HttpResponse,redirect

from app01.models import *
# Create your views here.

def add_publish(request):
    if request.method == 'POST':
        name=request.POST.get('name')
        addr=request.POST.get('addr')
        email=request.POST.get('email')
        Publish.objects.create(name=name,addr=addr,email=email)
        return redirect('/publish_list/')
    return render(request,'add_publish.html') #get

def publish_list(request):
    publish_list=Publish.objects.all()
    return render(request,'publish_list.html',{'publish_list':publish_list})

def delete_publish(request,nid):
    # nid=request.GET.get('nid')
    Publish.objects.filter(nid=nid).delete() #过滤出记录并删除
    return redirect('/publish_list/')

def edit_publish(request,pub_id):
    if request.method == 'POST':
        # nid=request.POST.get('nid')
        name=request.POST.get('name')
        addr=request.POST.get('addr')
        email=request.POST.get('email')
        Publish.objects.filter(pk=pub_id).update(name=name,addr=addr,email=email)
        return redirect('/publish_list/')
    # nid=request.GET.get('nid')
    publish = Publish.objects.filter(nid=pub_id).first() #对象
    return render(request,'edit_publish.html',{'publish':publish}) #渲染


def add_author(request):
    if request.method == 'POST':
        name=request.POST.get('name')
        age=request.POST.get('age')
        Author.objects.create(name=name,age=age)
        return redirect('/author_list/')
    return render(request,'add_author.html')

def author_list(request):
    author_list=Author.objects.all()
    return render(request,'author_list.html',{'author_list':author_list})

def delete_author(request):
    nid=request.GET.get('nid')
    Author.objects.filter(pk=nid).delete()
    return redirect('/author_list/')

def edit_author(request):
    if request.method == 'POST':
        nid=request.POST.get('nid')
        name=request.POST.get('name')
        age=request.POST.get('age')
        Author.objects.filter(pk=nid).update(name=name,age=age)
        return redirect('/author_list/')
    nid=request.GET.get('nid')
    author=Author.objects.filter(pk=nid).first()
    return render(request,'edit_author.html',{'author':author})


def add_book(request):
    if request.method == 'POST':
        name=request.POST.get('name')
        price=request.POST.get('price')
        pub_date=request.POST.get('pub_date')
        publish_id=request.POST.get('publish_id')
        authors=request.POST.getlist('authors') #这里传的是多个值
        book=Book.objects.create(name=name,price=price,pub_date=pub_date,publish_id=publish_id)

        book.authors.add(*authors) #向book2author表添加记录
        # for i in authors:
        #     book.authors.add(i)
        return redirect('/book_list/')
    publish_list=Publish.objects.all()
    author_list=Author.objects.all()
    return render(request,'add_book.html',{'publish_list':publish_list,'author_list':author_list})

def book_list(request):
    book_list=Book.objects.all()
    return render(request,'book_list.html',{'book_list':book_list})

def delete_book(request):
    nid=request.GET.get('nid')
    Book.objects.filter(pk=nid).delete()
    return redirect('/book_list/')

def edit_book(request):
    if request.method == 'POST':
        nid=request.POST.get('nid')
        name=request.POST.get('name')
        price=request.POST.get('price')
        pub_date=request.POST.get('pub_date')
        publish_id=request.POST.get('publish')
        authors=request.POST.getlist('authors')
        Book.objects.filter(pk=nid).update(name=name,price=price,pub_date=pub_date,publish_id=publish_id)
        book=Book.objects.filter(pk=nid).first()
        book.authors.set(authors)
        return redirect('/book_list/')
    nid=request.GET.get('nid')
    book=Book.objects.filter(pk=nid).first()
    publish_list=Publish.objects.all()
    author_list=Author.objects.all()
    return render(request,'edit_book.html',{'book':book,'publish_list':publish_list,'author_list':author_list})
views
"""
Django settings for djangotest04 project.

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

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

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/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/1.11/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'l)9jm)td9_(x^ysbafs%-@z56c#&)=ni#nn^pw(q8hn58(4k0g'

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


# Database
# https://docs.djangoproject.com/en/1.11/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/1.11/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/1.11/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/1.11/howto/static-files/

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

APPEND_SLASH=False
settings
"""djangotest04 URL Configuration

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

from app01 import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^add_publish/', views.add_publish),
    url(r'^add_author/', views.add_author),
    url(r'^add_book/', views.add_book),
    url(r'^publish_list/', views.publish_list),
    url(r'^author_list/', views.author_list),
    url(r'^book_list/', views.book_list),
    url(r'^delete_publish/(d+).html', views.delete_publish),
    url(r'^delete_author/', views.delete_author),
    url(r'^delete_book/', views.delete_book),
    url(r'^edit_publish/(?P<pub_id>d+).html', views.edit_publish),
    url(r'^edit_author/', views.edit_author),
    url(r'^edit_book/', views.edit_book),
]
urls
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>add_author</title>
    <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
</head>
<body>
    <div class="container" style="margin-top: 80px;">
        <div class="row">
            <div class="col-md-6 col-md-offset-3">
                <form action="/add_author/" method="post">
                    <p>name:<input type="text" name="name" class="form-control"></p>
                    <p>age:<input type="number" name="age" class="form-control"></p>
                    <p><input type="submit" value="add" class="form-control btn btn-success"></p>
                </form>
            </div>
        </div>
    </div>
</body>
</html>
add_author
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>add_book</title>
    <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
</head>
<body>
    <div class="container" style="margin-top: 80px;">
        <div class="row">
            <div class="col-md-6 col-md-offset-3">
                <form action="/add_book/" method="post">
                    <p>name:<input type="text" name="name" class="form-control"></p>
                    <p>price:<input type="text" name="price" class="form-control"></p>
                    <p>pub_date:<input type="date" name="pub_date" class="form-control"></p>

                    <p>publish_id:
                        <select name="publish_id" id="" class="form-control">
                            {% for publish in publish_list %}
                                <option value="{{ publish.nid }}">{{ publish.name }}</option>
                            {% endfor %}
                        </select>
                    </p>

                    <p>authors:
                        <select name="authors" id="" multiple class="form-control">
                            {% for author in author_list %}
                                <option value="{{ author.nid }}">{{ author.name }}</option>
                            {% endfor %}
                        </select>
                    </p>

                    <p><input type="submit" value="add" class="form-control btn btn-success"></p>
                </form>
            </div>
        </div>
    </div>
</body>
</html>
add_book
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>add_publish</title>
    <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
</head>
<body>
    <div class="container" style="margin-top: 80px;">
        <div class="row">
            <div class="col-md-6 col-md-offset-3">
                <form action="/add_publish/" method="post">
                    <p>name:<input type="text" name="name" class="form-control"></p>
                    <p>addr:<input type="text" name="addr" class="form-control"></p>
                    <p>email:<input type="text" name="email" class="form-control"></p>
                    <p><input type="submit" value="add" class="form-control btn btn-success"></p>
                </form>
            </div>
        </div>
    </div>
</body>
</html>
add_publish
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>author_list</title>
    <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
</head>
<body>
    <div class="container" style="margin-top: 80px;">
        <div class="row">
{#            <div class="col-md-6 col-md-offset-3 panel panel-default">#}
            <div class="col-md-6 col-md-offset-3">
                <table class="table table-condensed">
{#                <table class="table">#}
                    <thead>
                        <tr>
                            <th>nid</th>
                            <th>name</th>
                            <th>age</th>
                            <th>operation</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for author in author_list %}
                            <tr>
{#                                <td>{{ publish.nid }}</td>#}
                                {# id顺序展示 实际的id还是以数据库为准 没影响#}
                                <td>{{ forloop.counter }}</td>
                                <td>{{ author.name }}</td>
                                <td>{{ author.age }}</td>
                                <td>
                                    {# 点击跳转到指定的url并且携带参数  #}
                                    <a href="/delete_author/?nid={{ author.nid }}" class="btn btn-danger">删除</a>
                                    <a href="/edit_author/?nid={{ author.nid }}" class="btn btn-success">编辑</a>
                                </td>
                            </tr>
                        {% endfor %}

                    </tbody>
                </table>
            </div>
        </div>
    </div>
</body>
</html>
author_list
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>book_list</title>
    <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
</head>
<body>
    <div class="container" style="margin-top: 80px;">
        <div class="row">
{#            <div class="col-md-6 col-md-offset-3 panel panel-default">#}
            <div class="col-md-6 col-md-offset-3">
                <table class="table table-condensed">
{#                <table class="table">#}
                    <thead>
                        <tr>
                            <th>nid</th>
                            <th>name</th>
                            <th>price</th>
                            <th>pub_date</th>
                            <th>publish_name</th>
                            <th>author</th>
                            <th>operation</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for book in book_list %}
                            <tr>
{#                                <td>{{ publish.nid }}</td>#}
                                {# id顺序展示 实际的id还是以数据库为准 没影响#}
                                <td>{{ forloop.counter }}</td>
                                <td>{{ book.name }}</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 %}
                                        {{ author.name }}
                                    {% endfor %}

                                </td>
                                <td>
                                    {# 点击跳转到指定的url并且携带参数  #}
                                    <a href="/delete_book/?nid={{ book.nid }}" class="btn btn-danger">删除</a>
                                    <a href="/edit_book/?nid={{ book.nid }}" class="btn btn-success">编辑</a>
                                </td>
                            </tr>
                        {% endfor %}

                    </tbody>
                </table>
            </div>
        </div>
    </div>
</body>
</html>
book_list
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>edit_author</title>
    <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
</head>
<body>
    <div class="container" style="margin-top: 80px;">
        <div class="row">
            <div class="col-md-6 col-md-offset-3">
                <form action="/edit_author/" method="post">
                    <p><input type="hidden" name="nid" class="form-control" value="{{ author.nid }}"></p>
                    <p>name:<input type="text" name="name" class="form-control" value="{{ author.name }}"></p>
                    <p>age:<input type="text" name="age" class="form-control" value="{{ author.age }}"></p>
                    <p><input type="submit" value="edit" class="form-control btn btn-success"></p>
                </form>
            </div>
        </div>
    </div>
</body>
</html>
edit_author
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>edit_book</title>
    <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
</head>
<body>
    <div class="container" style="margin-top: 80px;">
        <div class="row">
            <div class="col-md-6 col-md-offset-3">
                <form action="/edit_book/" method="post">
                    <p><input type="hidden" name="nid" class="form-control" value="{{ book.nid }}"></p>
                    <p>name:<input type="text" name="name" class="form-control" value="{{ book.name }}"></p>
                    <p>price:<input type="text" name="price" class="form-control" value="{{ book.price }}"></p>
                    <p>pub_date:<input type="date" name="pub_date" class="form-control" value="{{ book.pub_date|date:'Y-m-d' }}"></p>

                    <p>publish:
                        <select name="publish" id="" class="form-control">
                            {% for publish in publish_list %}
                                {% if book.publish == publish %}
                                    <option selected value="{{ publish.nid }}">{{ publish.name }}</option>
                            {% else %}
                                    <option value="{{ publish.nid }}">{{ publish.name }}</option>
                                {% endif %}
                            {% endfor %}

                        </select>
                    </p>
                
                    <p>authors:
                        <select name="authors" id="" multiple class="form-control">
                            {% for author in author_list %}
                                {% if author in book.authors.all %}
                                    <option selected value="{{ author.nid }}">{{ author.name }}</option>
                                {% else %}
                                    <option value="{{ author.nid }}">{{ author.name }}</option>
                                {% endif %}
                            {% endfor %}
                            
                        </select>
                    </p>

                    <p><input type="submit" value="edit" class="form-control btn btn-success"></p>
                </form>
            </div>
        </div>
    </div>
</body>
</html>
edit_book
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>edit_publish</title>
    <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
</head>
<body>
    <div class="container" style="margin-top: 80px;">
        <div class="row">
            <div class="col-md-6 col-md-offset-3">
                <form action="/edit_publish/{{ publish.nid }}.html" method="post">
                    <p><input type="hidden" name="nid" class="form-control" value="{{ publish.nid }}"></p>
                    <p>name:<input type="text" name="name" class="form-control" value="{{ publish.name }}"></p>
                    <p>addr:<input type="text" name="addr" class="form-control" value="{{ publish.addr }}"></p>
                    <p>email:<input type="text" name="email" class="form-control" value="{{ publish.email }}"></p>
                    <p><input type="submit" value="edit" class="form-control btn btn-success"></p>
                </form>
            </div>
        </div>
    </div>
</body>
</html>
edit_publish
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>publish_list</title>
    <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
</head>
<body>
    <div class="container" style="margin-top: 80px;">
        <div class="row">
{#            <div class="col-md-6 col-md-offset-3 panel panel-default">#}
            <div class="col-md-6 col-md-offset-3">
                <table class="table table-condensed">
{#                <table class="table">#}
                    <thead>
                        <tr>
                            <th>nid</th>
                            <th>name</th>
                            <th>addr</th>
                            <th>email</th>
                            <th>operation</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for publish in publish_list %}
                            <tr>
{#                                <td>{{ publish.nid }}</td>#}
                                {# id顺序展示 实际的id还是以数据库为准 没影响#}
                                <td>{{ forloop.counter }}</td>
                                <td>{{ publish.name }}</td>
                                <td>{{ publish.addr }}</td>
                                <td>{{ publish.email }}</td>
                                <td>
                                    {# 点击跳转到指定的url并且携带参数  #}
{#                                    <a href="/delete_publish/?nid={{ publish.nid }}" class="btn btn-danger">删除</a>#}
                                    <a href="/delete_publish/{{ publish.nid }}.html" class="btn btn-danger">删除</a>
{#                                    <a href="/edit_publish/?nid={{ publish.nid }}" class="btn btn-success">编辑</a>#}
                                    <a href="/edit_publish/{{ publish.nid }}.html" class="btn btn-success">编辑</a>
                                </td>
                            </tr>
                        {% endfor %}

                    </tbody>
                </table>
            </div>
        </div>
    </div>
</body>
</html>
publish_list
原文地址:https://www.cnblogs.com/xujinjin18/p/9581891.html