1. 程式人生 > 其它 >Django——圖書管理系統(一)

Django——圖書管理系統(一)

技術標籤:Djangodjangocss3html5python圖書管理系統

首先,我們建立一個名為bookmanager的專案。命令列如下:

django-admin startproject bookmanager

接著,建立一個名為app01的APP,使用命令如下:

python manage.py startapp app01

然後,修改settings.py檔案如下所示:

"""
Django settings for bookmanager project.

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

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

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

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '2a%
[email protected]
(+f3yf)[email protected]_#0+pzur8_)_jsgcru' # 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', # 註釋掉csrf 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'bookmanager.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [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 = 'bookmanager.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'bookmanager', 'HOST': '127.0.0.1', 'PORT': 3306, 'USER': 'root', 'PASSWORD': '123456' } } # Password validation # https://docs.djangoproject.com/en/3.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/3.1/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/3.1/howto/static-files/ STATIC_URL = '/static/'

當然了,也別忘記在__init__.py檔案中加入下面的程式碼。

import pymysql
pymysql.install_as_MySQLdb()

好了,準備工作做完了。下面開始寫models。

在models.py檔案中新增下面的程式碼。

from django.db import models

# Create your models here.


class Publisher(models.Model):
    name = models.CharField(max_length=128)     # 出版社名稱

然後遷移資料庫,依舊是下面這兩條命令。

python manage.py makemigrations
>python manage.py migrate

向資料庫加入幾條資料,例如:

在views.py檔案中寫API

from django.shortcuts import render
from app01 import models


# Create your views here.


def publisher_list(request):
    obj = models.Publisher.objects.all()  # 獲取所有物件
    return render(request, 'publisher_list.html', {'publisher_list': obj})  # {'publisher_list': obj}是模板,可以傳遞給前端頁面。

然後在urls.py中寫路由

from django.contrib import admin
from django.urls import path
from app01 import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('publisher_list/', views.publisher_list),
]

publisher_list.html檔案內容如下所示:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<table border="1">
    <thead>
        <tr>
            <th>序號</th>
            <th>id</th>
            <th>出版社名稱</th>
        </tr>
    </thead>
    <tbody>
        {% for i in publisher_list %}   <!-- for迴圈來顯示出版社 -->
            <tr>
                <td>{{ forloop.counter }}</td>  <!-- 迴圈計數 -->
                <td>{{ i.id }}</td>     <!-- 取出id -->
                <td>{{ i.name }}</td>   <!-- 取出出版社名字 -->
            </tr>
        {% endfor %}        <!--  結束for迴圈  -->

    </tbody>
</table>
</body>
</html>

寫完這些以後,執行專案。可以得到如下的頁面。