作业35

图书管理系统

项目文件夹

settings.py

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 = '92#^(wcm_tpat^pi5qi63c61jygimb=0=aphz1keb9kyy(yg9e'

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

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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'day64',
        'USER': 'root',
        'PASSWORD': '\\',
        'HOST': '127.0.0.1',
        'PORT': 3306,
        'CHARSET': 'utf8'
    }
}

# 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/'

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.index,name='index'),
    url(r'^book_list/',views.book_list,name='book_list'),
    url(r'^add_book/', views.add_book,name='add_book'),
    url(r'^edit_book/(\d+)',views.edit_book,name='edit_book'),
    url(r'^delete_book/(\d+)',views.delete_book,name='delete_book')
]

__init__.py

import pymysql
pymysql.install_as_MySQLdb()

app01文件夹

models.py

from django.db import models


# Create your models here.
class Book(models.Model):
    name = models.CharField(max_length=32, verbose_name='书名')
    price = models.IntegerField(verbose_name='价格')
    publish_time = models.DateField(auto_now_add=True)
    authors = models.ManyToManyField(to='Author')
    publish = models.ForeignKey(to='Publish')

    # def __str__(self):
    #     return self.name


class Author(models.Model):
    name = models.CharField(max_length=32, verbose_name='作者姓名')
    age = models.IntegerField(verbose_name='年龄')
    author_detail = models.OneToOneField(to='AuthorDetail')


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


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

    # def __str__(self):
    #     return self.name

views.py

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


# Create your views here.


def index(request):
    return render(request, 'index.html')


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


def add_book(request):
    if request.method == 'POST':
        print(request.POST)
        name = request.POST.get('name')
        publish_date = request.POST.get('publish_date')
        price = request.POST.get('price')
        authors = request.POST.getlist('authors')
        publish = request.POST.get('publish')
        book_obj = models.Book.objects.create(name=name, publish_id=publish, price=price, publish_time=publish_date)
        book_obj.authors.add(*authors)
        return redirect('book_list')
    author_queryset = models.Author.objects.all()
    publish_queryset = models.Publish.objects.all()
    return render(request, 'add_book.html', locals())


def edit_book(request, edit_id):
    edit_book_obj = models.Book.objects.filter(pk=edit_id).first()
    if request.method == 'POST':
        print(request.POST)
        name = request.POST.get('name')
        publish_date = request.POST.get('publish_date')
        price = request.POST.get('price')
        authors = request.POST.getlist('authors')
        publish = request.POST.get('publish')
        models.Book.objects.filter(pk=edit_id).update(name=name, publish_id=publish, price=price,
                                                      publish_time=publish_date)
        edit_book_obj.authors.set(authors)
        return redirect('book_list')
    publish_queryset = models.Publish.objects.all()
    author_queryset = models.Author.objects.all()
    return render(request, 'edit_book.html', locals())


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

templates文件夹

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
    {% block css %}

    {% endblock %}
</head>
<body>
<div>
    <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="#">Brand</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="#">Link <span class="sr-only">(current)</span></a></li>
            <li><a href="#">Link</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="#">Link</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>
              </ul>
            </li>
          </ul>
        </div><!-- /.navbar-collapse -->
      </div><!-- /.container-fluid -->
    </nav>
</div>
<div class="container">
    <div class="row">
        <div class="col-md-3">
            <div class="list-group">
              <a href="#" class="list-group-item active">
                Cras justo odio
              </a>
              <a href="{% url 'index' %}" class="list-group-item">首页</a>
              <a href="{% url 'book_list' %}" class="list-group-item">书籍列表</a>
              <a href="#" class="list-group-item">Porta ac consectetur ac</a>
              <a href="#" class="list-group-item">Vestibulum at eros</a>
            </div>
        </div>
        <div class="col-md-8">
            <div class="panel panel-primary">
              <div class="panel-heading">
                <h3 class="panel-title">Panel title</h3>
              </div>
              <div class="panel-body">
                  {% block content %}
                    <div class="jumbotron">
                      <h1>Hello, world!</h1>
                      <p>...</p>
                      <p><a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a></p>
                    </div>
                  {% endblock %}
              </div>
            </div>
        </div>
    </div>
</div>
{% block js %}
    <script>

    </script>
{% endblock %}
</body>
</html>

book_list.html

{% extends 'index.html' %}
{% block content %}
    <a href="{% url 'add_book' %}" class="btn btn-success btn-xs">添加</a>
<table class="table table-hover table-striped">
    <thead>
        <tr>
            <th>id</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.id }}</td>
                <td>{{ book_obj.name }}</td>
                <td>{% for author_obj in book_obj.authors.all %}
                {{ author_obj.name }}
                {% endfor %}

                </td>
                <td>{{ book_obj.price }}</td>
                <td>{{ book_obj.publish.name }}</td>
                <td>{{ book_obj.publish_time|date:'Y-m-d' }}</td>
                <td>
                    <a href="{% url 'edit_book' book_obj.pk %}" class="btn btn-primary btn-xs">编辑</a>
                    <a href="{% url 'delete_book' book_obj.pk %}" class="btn btn-danger btn-xs">删除</a>
                </td>
            </tr>
        {% endfor %}
        
    </tbody>
</table>
{% endblock %}

add_book.html

{% extends 'index.html' %}
{% block content %}
<h1 class="text-center">添加书籍</h1>
    <form action="" method="post" enctype="multipart/form-data">
        <p>书籍名称: <input type="text" name="name" class="form-control"></p>
        <p>出版时间: <input type="date" name="publish_date" class="form-control"></p>
        <p>书籍价格: <input type="text" name="price" class="form-control"></p>
        <p>
            书籍作者:
            <select name="authors" id="" class="form-control" multiple>
                {% for author_obj in author_queryset %}
                    <option value="{{ author_obj.id }}">{{ author_obj.name }}</option>
                {% endfor %}
            </select>
        </p>
        <p>
            书籍出版社:
            <select name="publish" id="" class="form-control">
                {% for publish_obj in publish_queryset %}
                    <option value="{{ publish_obj.id }}">{{ publish_obj.name }}</option>
                {% endfor %}
            </select>
        </p>
        <button class="btn btn-success">提交</button>


    </form>
{% endblock %}

edit_book.html

{% extends 'index.html' %}
{% block content %}
<h1 class="text-center">编辑书籍</h1>
    <form action="" method="post">
        <p>书籍名称: <input type="text" name="name" class="form-control" value="{{ edit_book_obj.name }}"></p>
        <p>出版时间: <input type="date" name="publish_date" class="form-control" value="{{ edit_book_obj.publish_time|date:'Y-m-d' }}"></p>
        <p>书籍价格: <input type="text" name="price" class="form-control" value="{{ edit_book_obj.price }}"></p>
        <p>
            书籍作者:
            <select name="authors" id="" class="form-control" multiple>
                {% for author_obj in author_queryset %}
                    {% if author_obj in edit_book_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>
        <p>
            书籍出版社:
            <select name="publish" id="" class="form-control">
                {% for publish_obj in publish_queryset %}
                    {% if edit_book_obj.publish == publish_obj %}
                    <option value="{{ publish_obj.id }}" selected>{{ publish_obj.name }}</option>
                    {% else %}
                    <option value="{{ publish_obj.id }}">{{ publish_obj.name }}</option>
                    {% endif %}
                {% endfor %}
            </select>
        </p>
        <button class="btn btn-success">保存</button>
    </form>
{% endblock %}
 posted on 2020-06-02 23:32  wwwpy  阅读(176)  评论(0编辑  收藏  举报