2024年3月17日 星期日

用micro:bit來控制 micro:servo 360° EF90D

伺服馬達有區分成180° 和360° 兩種版本,購買是要特別小心。兩者的控制方式有很大不同,180° 伺服馬達不能用在需要連續運轉的場合,以樹藝創作為例:實作牛擺頭,就可以用180° 伺服馬達。而牛行動則可以採用360°版本的伺服馬達來實現。您可以參考:你知道180度舵機與360度舵機有什麼區別嗎?。就可以瞭解這兩種版本的伺服馬達的控制方式。

範例: micro:servo 360°的控制

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
from microbit import * 
pin0.set_analog_period(20)
pin0.write_analog(0)

while True: 
   pin0.write_analog(75)
   display.show(Image.ARROW_N)
   sleep(1000)
   pin0.write_analog(50)
   display.show(Image.ARROW_E)
   sleep(1000)
   pin0.write_analog(75)
   display.show(Image.ARROW_N)
   sleep(1000)
   pin0.write_analog(100)
   display.show(Image.ARROW_W)
   sleep(1000)
   pin0.write_analog(75)
   display.show(Image.ARROW_N)
   sleep(1000)

程式解說:
1.set_analog_period(20)是指設定類比訊號的週期20ms。
2.write_analog是指輸出類比訊號的責任週期,其中1023(100% duty cycle),0為0% dutycycle)。
3.pin0.write_analog(75)為停止,pin0.write_analog(50)為順時鐘旋轉,pin0.write_analog(100)為逆時鐘旋轉。

本實驗的360°伺服馬達是由奧斯丁提供。

2024年3月16日 星期六

用Python實現隨機座位表

 範例一、亂數產生1到45其中一個數字

1
2
import random
print(random.randint(1, 45))

執行結果:
29

範例二、亂數產生45個1到45數字

1
2
3
import random
for i in range(45):
    print(random.randint(1, 45), end=' ')

執行結果:
16 1 28 33 41 23 31 28 25 6 25 29 35 11 20 28 13 18 37 27 37 32 38 19 45 34 44 31 4 45 10 39 1 40 16 18 7 7 22 45 34 41 44 44 1

範例三、亂數產生45個1到45數字,不能有重複。

1
2
3
4
5
6
7
8
import random
SeatOrder = []
for i in range(45):
    number = random.randint(1, 45)
    while number in SeatOrder:
        number = random.randint(1, 45)
    SeatOrder.append(number) 
    print(number, end=' ')

執行結果:
12 39 43 9 18 38 27 17 13 30 8 10 45 11 15 28 31 32 33 2 26 36 44 16 20 6 40 37 22 4 1 35 25 29 21 19 14 42 24 5 7 34 23 41 3 

範例四、亂數產生45個1到45數字,不能有重複,每印出8個換行。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import random
SeatOrder = []
for i in range(45):
    number = random.randint(1, 45)
    while number in SeatOrder:
        number = random.randint(1, 45)
    SeatOrder.append(number)
    if (i+1) % 8:
        print(number, end=' ')
    else:
        print(number, end='\n')

執行結果:
43 5 20 45 13 35 29 42
36 11 17 24 3 31 8 4
1 39 28 30 32 26 12 44
2 15 33 27 23 37 41 10
21 18 38 6 7 14 19 9
16 22 34 25 40 

範例五、承上題,排列整齊

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import random
SeatOrder = []
for i in range(45):
    number = random.randint(1, 45)
    while number in SeatOrder:
        number = random.randint(1, 45)
    SeatOrder.append(number)
    if (i+1) % 8:
        print(f'{number:2}', end=' ')
    else:
        print(f'{number:2}', end='\n')

執行結果:


2024年3月15日 星期五

雙迴圈5*5實心方塊

範例一、利用Tutle指令來畫出5*5實心方塊

程式碼:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
import turtle
c = turtle.Turtle()
for i in range(1,6):
    for j in range(-2,3):
        c.penup()
        c.goto(-500+i*150,j*150)
        c.pendown()
        c.color("red")
        c.begin_fill()
        c.forward(100)
        c.left(90)
        c.forward(100)
        c.left(90)
        c.forward(100)
        c.left(90)
        c.forward(100)
        c.left(90)
        c.end_fill()

執行結果:

範例二、利用Tutle指令來畫出5*5實心方塊呈三角形

程式碼:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
import turtle
c = turtle.Turtle()
for i in range(1,6):
    for j in range(-2+i-1,3):
        c.penup()
        c.goto(-500+i*150,j*150)
        c.pendown()
        c.color("red")
        c.begin_fill()
        c.forward(100)
        c.left(90)
        c.forward(100)
        c.left(90)
        c.forward(100)
        c.left(90)
        c.forward(100)
        c.left(90)
        c.end_fill()

執行結果:



範例三、承上題,但中間的方不顯示

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import turtle
c = turtle.Turtle()
for i in range(1,6):
    for j in range(-2+i-1,3):
        if i==2 and j==-1:
            continue
        c.penup()
        c.goto(-500+i*150,j*150)
        c.pendown()
        c.color("red")
        c.begin_fill()
        c.forward(100)
        c.left(90)
        c.forward(100)
        c.left(90)
        c.forward(100)
        c.left(90)
        c.forward(100)
        c.left(90)
        c.end_fill()

執行結果:


2024年3月13日 星期三

善用pythonanywhere開發Django網站

1.pythonanywhere:https://www.pythonanywhere.com/


2.按下上圖的login,登錄或申請pythonanywhere的帳號


3.登入pythonanywhere,主要的功能有儀錶板(Dashboard)、主控台(Consoles)、檔案管理(Files)、網站(Web)、工作(Tasks)、資料庫(Database)。


4.選擇Web功能表單


5.選擇左手邊的Add a web app。


6.選擇右下角的Next


7.選擇Django


8.選擇Python 3.10(Django 4.0.6)


9.設定專案名稱和目錄,並按Next鍵。

10.可以按下cmlin.pythonanywhere.com,注意cmlin是使用者名稱。


11.請選擇右上方的Consloes選項。

12.選擇左上方的Bash來啟動主控台,並輸入python manage.py startapp myapp指令。

13.按下回上一頁,並選擇Files功能表單


14.選擇mysite目錄,並建立templates(可以利用new directory來建立)。

15.選擇templates,並建立index.html檔案。

16.選擇index.html,輸入HTML。

17.按下返回上一頁,選擇mysite目錄中的settings.py

完整的程式碼:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
"""
Django settings for mysite project.

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

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

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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-5hl#i+cv-9fvfe*8+kp2bw28i!1-(xcvi9f+iac*l5#1)*1+0w'

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

ALLOWED_HOSTS = ['cmlin.pythonanywhere.com']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp',
]

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


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/4.0/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/4.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


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

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# default static files settings for PythonAnywhere.
# see https://help.pythonanywhere.com/pages/DjangoStaticFiles for more info
MEDIA_ROOT = '/home/cmlin/mysite/media'
MEDIA_URL = '/media/'
STATIC_ROOT = '/home/cmlin/mysite/static'
STATIC_URL = '/static/'

18.存檔,按下返回上一頁,選擇mysite目錄中的urls.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
"""mysite URL Configuration

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

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

19.存檔,按下返回上一頁,選擇myapp目錄中的views.py

1
2
3
4
5
from django.shortcuts import render

# Create your views here.
def index(request):
    return render(request, "index.html", locals())

20.存檔,按下返回上一頁,選擇Web功能選單,再按下Reload鍵,開啟網站。



2024年3月6日 星期三

在Django網站首頁放置樹藝micro:bit的照片

2024年國立虎尾科技大學聯合樹藝工坊、台灣工藝創客青創基地以及奧斯丁國際共同組成樹藝micro:bit工藝創客團隊,正在執行樹藝與micro:bit的魔幻交織計畫。本計畫主題將結合micro:bit與傳統樹藝,用科技促進創新工藝與藝術表現。跨界合作、技術傳承、環保意識等來豐富臺灣工藝文化,提升工藝競爭力,讓藝術與科技共創實用作品。本篇文章以其中一張照片為主題來撰寫如何設計網站的首頁。

1.打開cmd,輸入mkvirtualenv django_image命令建立虛擬環境。


2.輸入pip install django建立Django套件。


3.輸入django-admin startproject django_image來建立Djano專案,利用cd django_image來切換目錄。


4.輸入Python manage.py startapp imageapp來建立應用程式。


5.利用mkdir指令來建立templates和static目錄


6.輸入python manage.py migrate指令進行模型(Model)與資料庫(Database)的同步。


7.輸入python manage.py runserver指令來啟動Server。


8.打開瀏覽器,輸入http://127.0.0.1:8000/網址,開啟首頁。


9. 修改django_image/settings.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
"""
Django settings for django_image project.

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

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

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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-27sk6k95gv+x%#)w-a-jz10%%)5v+7_hznd)g0_r!lsj5p$*g8'

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

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


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/5.0/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/5.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


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

STATIC_URL = 'static/'
STATICFILES_DIRS = [
    BASE_DIR/'static',
    ]

# Default primary key field type
# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

10.設定URL,django_image\urls.py。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
"""
URL configuration for django_image project.

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

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

註:路徑參數為空字串是代表首頁。

11.定義函式myapp\views.py。

1
2
3
4
5
from django.shortcuts import render

# Create your views here.
def index(request):
    return render(request, "index.html", locals())

12.把下列照片放到static目錄中,檔案名稱monkey.jpg。

13.撰寫下列HTML,儲存在templates目錄中,取名為index.html。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<! DOCTYPE html>
<html>
<head>
<title>
樹藝和micro:bit
</title>
</head>
<body>
<h1>樹藝和micro:bit<h1>
<img src="static/monkey.jpg">
</body>
</html>

14.重新整理網頁

15.在View中傳送變數到樣版。
15.1修改imageapp/views.py

1
2
3
4
5
6
7
from django.shortcuts import render

# Create your views here.
def index(request):
    h1_title = "樹藝和micro:bit"
    jpg_name = "monkey.jpg"
    return render(request, "index.html", locals())

15.2修改templates/index.html
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<! DOCTYPE html>
<html>
<head>
<title>
樹藝和micro:bit
</title>
</head>
<body>
<h1>{{h1_title}}<h1>
<img src="static/{{jpg_name}}">
</body>
</html>


15.3重新整理

16.使用load static指令
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<! DOCTYPE html>
<html>
<head>
<title>
樹藝和micro:bit
</title>
{% load static %}
</head>
<body>
<h1>{{h1_title}}<h1>
<img src={% static "" %}{{jpg_name}}>
</body>
</html>

重新整理


2024年2月24日 星期六

Django 5.0:建置學生通訊錄資料庫

參考資料:Python架站特訓班django最強實戰

1..打開cmd,輸入mkvirtualenv django_first命令建立虛擬環境。


2.輸入pip install django建立Django套件。


3.輸入django-admin startproject students來建立Djano專案,利用cd students來切換目錄。


4.輸入Python manage.py startapp studentsapp來建立應用程式。


5.輸入python manage.py migrate指令進行模型(Model)與資料庫(Database)的同步。


6.輸入python manage.py runserver指令來啟動Server。


7.打開瀏覽器,輸入http://127.0.0.1:8000/網址,開啟首頁。


8. 修改students/settings.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
"""
Django settings for students project.

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

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

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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-52y=6w_01z!@bcyzkrs@eyl(^s0li20(i8$gokwhbvw-gcj59h'

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

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


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/5.0/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/5.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


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

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

9.在students/urls.py新增一條鏈結。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
"""
URL configuration for students project.

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

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

10.在studentsapp/views.py下,新增index()函式。

1
2
3
4
5
6
7
8
from django.shortcuts import render
from studentsapp.models import student

# Create your views here.

def index(request):
    students = student.objects.all().order_by('id')
    return render(request, "index.html", locals())

11.在studentsapp/models.py下,新增student資料模型。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from django.db import models

# Create your models here.
class student(models.Model):
    cName = models.CharField(max_length = 20, null = False)
    cSex = models.CharField(max_length = 2, default = 'M', null = False)
    cBirthday = models.DateField(null = False)
    cEmail = models.CharField(max_length = 50, blank = True, default = '')
    cPhone = models.CharField(max_length = 50, blank = True, default = '')
    cAddr = models.CharField(max_length = 255, blank = True, default = '')

    def __str__(self):
        return self.cName

12.重新整理網頁

在執行網站的cmd畫面中,也看到錯誤訊息

13.模型與資料庫同步,請執行下列命令:
python manage.py makemigrations
python manage.py migrates

14.重新整理畫面

15.新增超級使用者帳號
python manage.py createsuperuser
帳號:admin
密碼:1234

15.在studentsapp/admin.py新增後台管理student資料庫的程式

1
2
3
4
5
from django.contrib import admin
from studentsapp.models import student

# Register your models here.
admin.site.register(student)

16.登錄後台

17.查看student資料庫

18.按下上圖students旁的Add鈕,新增一筆資料。

19.按下上圖的SAVE鈕。

20.重新整理前台畫面