Django-作业图书管理系统

实现功能:book单表的增删改查

项目urls.py :转到app01的urls里面去分发

from django.contrib import admin
from django.urls import path,include
from app01 import urls

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('app01.urls'))
]

app01/urls.py

from django.contrib import admin
from django.urls import path,re_path
from app01 import views

urlpatterns = [
    path('books/', views.books),  #主页
    re_path(r'books/(\d+)/delete', views.delbook), # 删除
    re_path(r'books/(\d+)/change', views.changebook), # 修改

]

sttings.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/2.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'c#)irf!fu$48339(s9^0x=c%9&s*@3(4=w4&0uw4qr3m*lo#1o'

# 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',  # app01 绑定
] 

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


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

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


#数据库配置
DATABASES = { 'default':{ 'ENGINE':'django.db.backends.mysql', #引擎 指定引擎 'NAME':'book', # 要连接的数据库,连接前需要先创建好 'USER':'root', # 连接数据库的用户名 'PASSWORD':'123456', # 连接数据库的密码 'HOST':'127.0.0.1', # 连接主机 'PORT':3306 # 端口 } } STATIC_URL = '/static/' #静态文件 配置 默认的

#数据库log LOGGING
= { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console':{ 'level':'DEBUG', 'class':'logging.StreamHandler', }, }, 'loggers': { 'django.db.backends': { 'handlers': ['console'], 'propagate': True, 'level':'DEBUG', }, } }

app01/models.py

from django.db import models

# Create your models here.


class Book(models.Model):
    id = models.AutoField(primary_key=True) #递增的id号
    title = models.CharField(max_length=32) #书籍名字
    pub_date = models.DateField()           #时间
    price = models.DecimalField(max_digits=8, decimal_places=2) #价格
    publish = models.CharField(max_length=32) #出版社

app01/views.py

from django.shortcuts import render,HttpResponse,redirect #redirect 重定向页面

# Create your views here.

from app01.models import Book

#先有数据,才能查出来数据 所以 先写addbooks函数
def addbooks(request):

    if request.method == "POST":
        title= request.POST.get("title")
        date=request.POST.get("date")
        price=request.POST.get("price")
        publish=request.POST.get("press")

        book_obj=Book.objects.create(title=title,pub_date=date,price=price,publish=publish)
        return redirect("/books/")  #返回一个地址 ,如果是post提交 就把数据都创建上,写在数据库里面
    return  render(request,"addbook.html")  #直接访问添加页面 返回这个


def books(request):
    res = Book.objects.all().filter()  # 拿出来的是对象 通过模版翻译 在模版里可直接循环 调出数据值
    return render(request,'books.html',locals()) #主页


def delbook(request,id):
Book.objects.filter(id
=id).delete() #根据id号 唯一的id号 查出来 删除掉 删除完成不需要返回什么页面 还是返回主页面所以。。。 return redirect("/books/")    #直接redirect 函数 返回一个路径 让页面去再去访问一次 得到主页面 #redirect 重定向 def changebook(request,id):     res = Book.objects.filter(id=id).first() #根据id号查出来 查出来的是一个对象 用作编辑页面里面的内容填写 对象带入模版语法 进行渲染 if request.method == "POST": title= request.POST.get("title") date=request.POST.get("date") price=request.POST.get("price") publish=request.POST.get("press") Book.objects.filter(id=id).update(title=title,pub_date=date,price=price,publish=publish) return redirect("/books/") return render(request,'editbook.html',{"res":res}) #res 是对象 带入模版语法 进行渲染

页面1 books.html

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="/static/books_obj/css/reset.css" type="text/css">
    <link rel="stylesheet" href="/static/books_obj/css/books.css" type="text/css">
    <meta charset="UTF-8">
    <title>图书管理系统</title>
</head>
<body>
<div>
    <h2>- 图书管理系统 -</h2>
</div>

<div class="one_center">
    <div class="two_center">
        <table class="table_center" border="1">
        
                  页面提交到 addbook 函数中 直接返回添加书籍目录 <span><a href="/addbook/"> 添加书籍 </a> </span> <tr class="tr_1"> <th>书籍名称</th> <th>价格</th> <th>出版日期</th> <th>出版社</th> <th>删除操作</th> <th>编辑</th> </tr> <tbody>
        
            # 每次循环 是一个QuerySet对象 每次循环都会渲染出td标签和里面的内容 {% for i in res %} <tr class="tr_2"> <td>{{ i.title }}</td> <td>{{ i.price }}</td> <td>{{ i.pub_date |date:'Y-m-d'}}</td> <td>{{ i.publish }}</td> {# i.pk 代表主键 等同与i.id#} <td><a href="books/{{ i.pk }}/delete">删除操作</a></td> <td><a href="books/{{ i.pk }}/change">编辑</a></td> </tr> {% endfor %} </tbody> </table> </div> </div> </body> </html>

页面2 addbooks.html

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="/static/books_obj/css/reset.css" >
    <link rel="stylesheet" href="/static/books_obj/css/addbook.css" >
    
    <meta charset="UTF-8">
    <title>添加书籍</title>
    
</head>
<body>
<h3>- 添加书籍 - </h3>
    <form action="#" method="post">
        {% csrf_token %} {#防跨域请求#}
        <div>
            <span>书籍名字</span>
            <input type="text" name="title">
        </div>
        <div>
            <span>价格</span>
            <input type="text" name="price">
        </div>
        <div>
            <span>出版日期</span>
            <input type="date" name="date">
        </div>
        <div>
            <span>出版社</span>
            <input type="text" name="press">
        </div>
        <input type="submit" class="btn_btn-success_pull-right">
    </form>
</body>
</html>

页面3 editbooks.html

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="/static/books_obj/css/reset.css" >
    <link rel="stylesheet" href="/static/books_obj/css/addbook.css" >
    
    <meta charset="UTF-8">
    <title>修改书籍</title>
    
</head>
<body>
<h3>- 修改书籍 - </h3>
    <form action="#" method="post">  #还是提交当前页面 因为changebook函数 里面做if 可以判断你是post请求还是get请求 
         {% csrf_token %} {#防跨域请求#}
        <div>
            <span>书籍名字</span>
            <input type="text" name="title" value="{{ res.title }}">
        </div>
        <div>
            <span>价格</span>
            <input type="text" name="price" value="{{ res.price }}">
        </div>
        <div>
            <span>出版日期</span>
            <input type="date" name="date" value="{{ res.pub_date |date:"Y-m-d" }}">
        </div>
        <div>
            <span>出版社</span>
            <input type="text" name="press" value="{{ res.publish }}">
        </div>
        <input type="submit" class="btn_btn-success_pull-right" value="修改">
    </form>
</body>
</html>

css 样式 联系我

posted on 2020-10-19 14:12  I我非柠檬为何心酸I  阅读(155)  评论(0编辑  收藏  举报