书架项目代码


项目代码
提取码:szl2

1.创建项目

"""打开一个shell 窗口,切换到桌面,或者其他存放项目的地方
	创建一个文件夹
	
	1. ctrl+alt+T 打开一个命令窗口
	2. cd ~/桌面/
	3. mkdir myproject #名字自定义
	4. cd myproject
	5. django-admin startproject bookstore 创建项目
	6. cd bookstore
	7. python3 manage.py runserver  #默认127.0.0.1:8000端口启动
	8. 打开浏览器,地址栏输入:127.0.0.1:8000
	若有如下页面,则项目创建成功
"""

在这里插入图片描述

2.配置项目

使用pycharm 打开项目
file>open>找到项目根目录> 打开
整体目录结构如下:
在这里插入图片描述
settings.py 项目的配置文件
urls.py 项目的主路由文件,请求进入django 的入口
wsgi.py 项目应用程序与服务程序的约定协议,正式启动服务时使用

settings.py

"""
Django settings for bookstore project.

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

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

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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'oq)%+g4_m#(_1=za=%a(3+pu@xbwy8#tj)r58t-8&^sbum9^(p'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True  #开发模式

ALLOWED_HOSTS = ["*"] #允许请求哪些Host地址的请求进入django

# Application definition
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    "book",  #安装应用
]

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 = 'bookstore.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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 = 'bookstore.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
"""
#配置mysql数据库
#django 连接mysql 使用mysqlclient库 1.3.13以上版本
#安装mysqlclient之前需在linux系统环境安装
#libmysqlclient-dev    否则报错mysql_config
#default-libmysqlcient-dev
#python3-dev
#查看linux系统环境是否安装 以上两个库
#sudo apt list --installed | grep -E "mysqlclient|python3-dev"

#然后sudo pip3 install mysqlclient
#sudo pip3 list |grep -i "mysqlclient"
"""
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME':"bookstore", #先创建一个bookstore数据库
        "HOST":"localhost",
        "PORT":"3306",
        "USER":"lauf",
        "PASSWORD":"lauf123",
        "CHARSET":"utf8",
    }
}


# 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',
    },
]


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

LANGUAGE_CODE = 'zh-Hans'  #显示中文

TIME_ZONE = 'Asia/Shanghai' #本地时间

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/

#url that starts with "static"
#is for the static resource

#配置静态文件
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR,"static"),)


3.创建应用

  1. 在项目根目录下,创建book应用
python3 manage.py startapp book

目录结构如下:
在这里插入图片描述
admin.py 注册模型类,实现后台的管理
models.py 定义模型类,操作db
urls.py 应用下的路由,定义路由模式
views.py 应用下的视图,定义视图函数
migrations 实现ORM映射的迁移文件
templates 自己创建的模板

在配置文件中安装应用

  1. 创建模型类,处理book应用的数据
from django.db import models

# Create your models here.
class Book(models.Model):

    title = models.CharField("书名",max_length=50)
    author = models.CharField("作者",max_length=10)
    publish_time = models.DateTimeField("出版时间",auto_now_add=True)
    update_time = models.DateTimeField("更新时间",auto_now=True)

    publish_depart = models.ForeignKey("PubDepart",on_delete=models.CASCADE,default="清华大学出版社")
    is_delete = models.BooleanField("删除",default=False)

    def __str__(self):
        return self.title

    class Meta:
        db_table = "book_table"


class PubDepart(models.Model):

    name = models.CharField("出版社",max_length=30)
    addr = models.CharField("地址",max_length=100)

    def __str__(self):
        return self.name

    class Meta:
        db_table = "publish_depart"


  1. 数据迁移
python3 manage.py makemigrations #生成迁移文件,映射为sql
python3 manage.py migrate #执行sql

4.查看bookstore 数据库,是否增加预期的表

#连接mysql
sudo mysql -u lauf -p 

>use bookstore;
>show tables;
>desc book_table;

4.配置分布式路由

1.配置主路由urls.py

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path("index/",include("book.urls")),
    path("book/",include("book.urls")),
]
  1. 配置book/urls.py
from django.urls import path,include
from django.conf.urls import url
from book.views import *

urlpatterns = [
    #show book list
    path("",index),
    path("list/",index),
   
    #update book
    path("update/",update),
    #delete book
    path("delete/",delete),
    #add book
    path("add/",add),
]

5.定义视图函数

在book应用下views.py,分别定义index,update,delete,add 视图函数

from django.shortcuts import render
from django.http import HttpResponse
from django.http import JsonResponse
from django.http import HttpResponseRedirect
from book.models import Book
from book.models import PubDepart
from datetime import datetime
import json

# Create your views here.
#10010 记录不存在

def index(request):  #第一个参数request,为请求对象
    #get method
    if request.method == "GET":
        #查询没有删除的数据
        all_books = Book.objects.filter(is_delete=False)
        if all_books:
            data = {"books":all_books}
            #查询所有的书籍,并显示

            return render(request,"book/index.html",data)
        else:
            return HttpResponse("空空如也")

    else:

        return HttpResponse("received your request")

def update(request):

    if request.method == "GET":

        #获取查询参数
        title = request.GET.get("title")

        #没有查询字符串
        if title is None:
            return HttpResponse("需要指定查询参数")

        #查询数据
        try:
            b = Book.objects.get(title=title)
        except:
            data = {"code":10010,"error":"数据不存在"}
            return render(request,"book/blank.html",data)
        else:
            data = {"code":200,"data":{"id":b.id,"title":b.title,"author":b.author,"publish_time":datetime.strftime(b.publish_time,"%Y-%m-%d %H:%M:%S")}}

        return render(request,"book/update.html",data)

    elif request.method == "POST":

        #获取post提交的数据
        # title = request.POST.get("title")
        # author = request.POST.get("author")
        # publish_time = request.POST.get("publish_time")
        json_str = request.body
        print("json_str:",json_str)

        #字典
        json_obj = json.loads(json_str)
        # print("xxxxx",type(json_obj))

        id_ = json_obj.get("id")
        title = json_obj.get("title")
        author = json_obj.get("author")
        #处理字符串时间
        publish_time = json_obj.get("publish_time")

        print("提交的数据-----------")
        print(title)
        print(author)
        #query db
        try:
            b = Book.objects.get(id=id_)
        except:
            data = {"code":10010,"error":"记录不存在"}
            return JsonResponse(data)

        #更新数据对象
        b.title = title
        b.author = author
        b.publish_time = publish_time
        b.save()

        data = {"code":200,"data":"更新成功"}
        return JsonResponse(data)

def delete(request):
    #获取查询字符串的参数
    title = request.GET.get("title")

    if title is None:
        return HttpResponse("需要指定参数")

    #查询db
    try:
        b = Book.objects.get(title=title)

    except:
        #数据不存在
        data = {"code":10010,"error":"数据不存在"}
        return JsonResponse(data)
    else:
        try:
            b.is_delete = True
            b.save()
        except:
            data = {"code":10012,"data":"删除失败"}
            return JsonResponse(data)
    data = {"code":200,"data":"删除成功"}

    return JsonResponse(data)


def add(request):

    #get 请求
    if request.method == "GET":
        return render(request,"book/add_book.html")
    #post 请求
    elif request.method == "POST":

        json_str = request.body
        json_obj = json.loads(json_str)


        title = json_obj.get("title")
        author = json_obj.get("author")
        if not title or not author:
            data = {"code":10014,"error":"信息不完整"}
            return JsonResponse(data)

        #字符串时间
        publish_time = json_obj.get("publish_time")

        #1/2
        publish_depart = json_obj.get("publish_depart")


        #查询当前的书名是否存在于db
        #若存在,则只需将 is_delete 字段 设置为False
        try:
            b = Book.objects.get(title=title)
            if b.is_delete:
                b.is_delete = False
                b.save()
            else:
                data = {"code":10015,"error":"数据已存在"}
                return JsonResponse(data)
        except:
            # 外键必须给对象
            refer_obj = PubDepart.objects.get(id=publish_depart)
            try:
                #添加数据
                Book.objects.create(title=title,author=author,publish_time=publish_time,publish_depart=refer_obj)
            except:
                data = {"code":10013,"error":"添加失败"}
                return JsonResponse(data)

        data = {"code":200,"data":"添加成功"}

    return JsonResponse(data)

6.创建模板页面

在应用book/templates/book/ 目录下添加模板页面

xxx.html
模板

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

laufing

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值