<<< 上一章節(jié),我們已經(jīng)成功搭建好網(wǎng)站的開發(fā)環(huán)境
本章節(jié)我們開始創(chuàng)建網(wǎng)站
建站第一步
現(xiàn)在我們來做一個簡單的備忘筆記網(wǎng)站sthtodo
,我們用Django的管理工具django-admin.py
創(chuàng)建這個項目
$ django-admin.py startproject sthtodo
創(chuàng)建完成后,我們進(jìn)入sthtodo
項目,并查看sthtodo
項目的目錄結(jié)構(gòu)
$ cd sthtodo
$ tree
目錄顯示和說明
(sthtodo) vagrant@precise64:~/sthtodo$ tree
.
|-- manage.py # 項目最重要的命令行管理工具
`-- sthtodo # 項目的包sthtodo
|-- __init__.py # 包的初始化文件
|-- settings.py # 項目的主要配置文件
|-- urls.py # 項目的url管理文件
`-- wsgi.py # Web服務(wù)器的入口
1 directory, 5 files
啟動開發(fā)服務(wù)器,運(yùn)行項目
$ python manage.py runserver 0.0.0.0:8000
其中IP地址0.0.0.0
可以讓同網(wǎng)絡(luò)下的其它設(shè)備連接到開發(fā)服務(wù)器上,8000
是端口號,如果IP地址和端口號不聲明,程序就默認(rèn)使用IP地址127.0.0.1
和端口號8000
,這時命令行顯示如下,先忽略You have 13 unapplied migration(s)...
這段文字,開發(fā)服務(wù)器并沒有報錯,成功啟動
(sthtodo) vagrant@precise64:~/sthtodo$ python manage.py runserver 0.0.0.0:8000
Performing system checks...
System check identified no issues (0 silenced).
You have 13 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
February 16, 2019 - 19:36:46
Django version 1.11.8, using settings 'sthtodo.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.
打開瀏覽器鍵入127.0.0.1:8000
或localhost:8000
,顯示如下
這時再留意命令行,多出一行頁面請求的信息
Django version 1.11.8, using settings 'sthtodo.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.
[16/Feb/2019 19:42:21] "GET / HTTP/1.1" 200 1716
使用Git管理項目代碼
Git是目前最受開發(fā)者歡迎和廣泛使用的分布式版本控制系統(tǒng),對于項目本身來說,它可以把項目代碼備份到云端,同時儲存每一次項目代碼的改動,為項目的管理和多人協(xié)作提供了便利,接下來簡單介紹如何用Git管理你的項目。
安裝Git
Windows系統(tǒng)可以在官網(wǎng)的下載頁下載安裝,安裝完成后可以在開始菜單里找到Git => Git Bash (也可以直接點(diǎn)擊鼠標(biāo)右鍵進(jìn)入),如果彈出命令行窗口即安裝成功,然后就可以用Git的命令行開始項目管理。
Mac OS系統(tǒng),用Homebrew來安裝
$ brew install git
Linux系統(tǒng),用APT安裝
$ sudo apt-get install git
用戶信息配置
做為分布式管理系統(tǒng),每個使用Git的用戶設(shè)備都建議完善基本信息:用戶名和Email郵箱,配置命令如下
$ git config --global user.name "Your Name"
$ git config --global user.email "email@example.com"
創(chuàng)建遠(yuǎn)程倉庫
使用Git管理項目代碼,當(dāng)然少不了在代碼托管網(wǎng)站Github上建立遠(yuǎn)程倉庫,首先你需要進(jìn)入網(wǎng)站注冊一個賬號。
由于你電腦上安裝的Git和Github遠(yuǎn)程倉庫之間的傳輸是通過SSH加密的,所以我們需要一些配置:
- 創(chuàng)建SSH Key
$ ssh-keygen -t rsa -C "your_email@example.com"
首先,你需要把郵箱地址換成你在Github上注冊的地址再回車,然后會有路徑確認(rèn)和輸入密碼的提示,你可以選擇忽略,一路回車就行,如果一切順利的話,用戶主目錄中將生成.ssh
子目錄
vagrant@precise64:~$ ssh-keygen -t rsa -C "harry4769@gmail.com"
Generating public/private rsa key pair.
Enter file in which to save the key (/home/vagrant/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/vagrant/.ssh/id_rsa.
Your public key has been saved in /home/vagrant/.ssh/id_rsa.pub.
The key fingerprint is:
......
- 打開該子目錄中的文件
id_rsa.pub
,復(fù)制里面的內(nèi)容
vagrant@precise64:~$ ls /home/vagrant/.ssh
authorized_keys id_rsa id_rsa.pub
vagrant@precise64:~$ vi /home/vagrant/.ssh/id_rsa.pub
回到Github注冊好的賬戶中,進(jìn)入
Account
=>Settings
=>SSH and CPG keys
,點(diǎn)擊New SSH key
接著
Title
可以隨便填,剛才復(fù)制的內(nèi)容粘貼到Key
下面,點(diǎn)擊Add SSH key
,最后你可以看到已經(jīng)添加好的Key
,添加成功配置完成,接下來就是創(chuàng)建管理項目的倉庫
Repository
,點(diǎn)擊右上角的+ (加號)
,選擇New repository
,即可創(chuàng)建倉庫
推送項目代碼
當(dāng)Github遠(yuǎn)程倉庫成功創(chuàng)建,我們就需要用Git命令把本地的項目代碼推送到遠(yuǎn)程倉庫
初始化Git倉庫
$ git init
關(guān)聯(lián)遠(yuǎn)程倉庫
$ git remote add origin git@github.com:your_name/sthtodo.git
獲取遠(yuǎn)程倉庫的更新
$ git pull origin master
查看項目的改動狀態(tài)
$ git status
將所有改動的文件添加到緩存區(qū)
$ git add -A
將緩存區(qū)內(nèi)容添加到本地倉庫并提交注釋
$ git commit -m "Start project sthtodo"
最后把本地倉庫的內(nèi)容推送到遠(yuǎn)程倉庫
$ git push origin master
這時訪問Github上的遠(yuǎn)程倉庫,如果顯示剛才提交的更新,就推送成功了。
遠(yuǎn)程倉庫克隆
如果我們需要把項目代碼轉(zhuǎn)移到其它電腦,或者項目同時需要多人測試開發(fā),最好的方式就是從遠(yuǎn)程倉庫克隆項目代碼
$ git clone git@github.com:your_name/sthtodo.git
網(wǎng)站項目的自定義化
Django做為輕量級的Web框架,本身已經(jīng)架構(gòu)好Web程序的核心部分,而我們只需要掌握Python的基本語法和程序設(shè)計的基礎(chǔ)邏輯,就可以進(jìn)行高效敏捷的開發(fā)。
MVC/MTV設(shè)計模式
MVC是針對高效的Web開發(fā)而廣泛運(yùn)用的設(shè)計模式,其中M代表Model(模型,負(fù)責(zé)連接數(shù)據(jù)庫),V代表View(視圖,負(fù)責(zé)頁面的交互),C代表Controller(控制器,負(fù)責(zé)用戶的請求),這三者看似相互獨(dú)立,卻通過簡單的配置管理工具緊密結(jié)合在一起,構(gòu)成Web項目的整體。
而對于Django的MTV模式,結(jié)合和構(gòu)成方式與MVC是一致的,只是在定義上有所區(qū)別,M依然代表Model(模型,負(fù)責(zé)連接數(shù)據(jù)庫),T代表Template(模板,負(fù)責(zé)把頁面展示給用戶),V代表View(視圖,負(fù)責(zé)后端邏輯,會調(diào)用Model和Template)。
除此之外Django框架還包含一個URL分發(fā)器,它負(fù)責(zé)將網(wǎng)址URL的頁面請求分發(fā)給相應(yīng)的View處理,View再調(diào)用相應(yīng)的Model和Template,同時你還需要配置Static Files(靜態(tài)文件),它負(fù)責(zé)頁面的樣式布局和前端交互。
綜上所述,我們根據(jù)這些基本要素,就可以進(jìn)行自定義化的修改配置,實現(xiàn)動態(tài)交互的網(wǎng)站頁面。
運(yùn)用分支管理項目的修改
在項目自定義化修改配置之前,我們用Git在本地倉庫新建一個分支config
$ git checkout -b config
這行命令回車之后,本地倉庫的新分支config
便成功創(chuàng)建,并且直接從master
主分支切換到config
分支,這時候,我們就可以正式開始項目的修改。
創(chuàng)建新應(yīng)用(startapp)
現(xiàn)在,我們?yōu)?code>sthtodo項目創(chuàng)建兩個應(yīng)用home
和note
$ python manage.py startapp home
$ python manage.py startapp note
這時可以看到sthtodo
主目錄中多出兩個文件夾home
和note
,查看這兩個文件夾包含的所有文件
(sthtodo) vagrant@precise64:~/sthtodo$ python manage.py startapp home
(sthtodo) vagrant@precise64:~/sthtodo$ python manage.py startapp note
(sthtodo) vagrant@precise64:~/sthtodo$ ls
README.md home note
db.sqlite3 manage.py sthtodo
(sthtodo) vagrant@precise64:~/sthtodo$ tree home
home
├── __init__.py
├── admin.py
├── apps.py
├── migrations
│ └── __init__.py
├── models.py
├── tests.py
└── views.py
1 directory, 7 files
(sthtodo) vagrant@precise64:~/sthtodo$ tree note
note
├── __init__.py
├── admin.py
├── apps.py
├── migrations
│ └── __init__.py
├── models.py
├── tests.py
└── views.py
1 directory, 7 files
用Git查看改動狀態(tài)
(sthtodo) vagrant@precise64:~/sthtodo$ git status
On branch config
Untracked files:
(use "git add <file>..." to include in what will be committed)
home/
note/
nothing added to commit but untracked files present (use "git add" to track)
提交修改,并推送到Github遠(yuǎn)程倉庫
(sthtodo) vagrant@precise64:~/sthtodo$ git add -A
(sthtodo) vagrant@precise64:~/sthtodo$ git commit -m "Start app home and note"
[config 6419421] Start app home and note
14 files changed, 34 insertions(+)
create mode 100644 home/__init__.py
create mode 100644 home/admin.py
create mode 100644 home/apps.py
create mode 100644 home/migrations/__init__.py
create mode 100644 home/models.py
create mode 100644 home/tests.py
create mode 100644 home/views.py
create mode 100644 note/__init__.py
create mode 100644 note/admin.py
create mode 100644 note/apps.py
create mode 100644 note/migrations/__init__.py
create mode 100644 note/models.py
create mode 100644 note/tests.py
create mode 100644 note/views.py
(sthtodo) vagrant@precise64:~/sthtodo$ git push origin config
Counting objects: 11, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (10/10), done.
Writing objects: 100% (11/11), 1.03 KiB | 350.00 KiB/s, done.
Total 11 (delta 2), reused 0 (delta 0)
remote: Resolving deltas: 100% (2/2), completed with 1 local object.
remote:
remote: Create a pull request for 'config' on GitHub by visiting:
remote: https://github.com/harryhmx/sthtodo/pull/new/config
remote:
To github.com:harryhmx/sthtodo.git
* [new branch] config -> config
模板(Template)
Django的MTV模式中,模板(T/Template)的作用是展示給用戶交互的頁面,通常它是一個html格式的文本,通過瀏覽器的解析顯示文字和圖片的頁面,在我們創(chuàng)建模板之前,需要一些配置。
配置模板信息
打開子目錄sthtodo
下的配置文件settings.py
"""
Django settings for sthtodo project.
Generated by 'django-admin startproject' using Django 1.11.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/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__)))
...
截取該文件代碼的開頭幾行,注意到變量BASE_DIR
,它是項目sthtodo
主目錄的絕對路徑,我們往下翻,找到變量TEMPLATES
,在DIRS
后面的方括號里添加os.path.join(BASE_DIR, 'templates')
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',
],
},
},
]
然后,在主目錄下創(chuàng)建新的子目錄templates
,接下來添加的模板文件統(tǒng)一放在該子目錄下
$ mkdir templates
添加模板
首先對于網(wǎng)站的模板設(shè)計,一般會有一些通用部分,我們先添加第一個通用模板base.html
$ touch templates/base.html
打開通用模板base.html
,添加如下代碼
<!DOCTYPE html>
<html>
{% include "head.html" %}
<body>
{% block main_body %}{% endblock %}
</body>
</html>
以上代碼中,{% include %}
標(biāo)簽表示包含其它模板的內(nèi)容,也就是接下來創(chuàng)建的第二個通用模板head.html
,而名為main_body
的{% block %}
標(biāo)簽則用于接下來創(chuàng)建的繼承模板index.html
和note.html
重寫替換的部分。
接著,創(chuàng)建第二個通用模板head.html
$ touch templates/head.html
添加代碼
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"/>
<title>{{ head_title|default:'Sthtodo' }}</title>
<!-- Bootstrap CSS -->
<link rel="stylesheet"/>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="http://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="http://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
這段代碼中,雙括號{{}}
中的head_title
是變量,|
是過濾器符號,default
是過濾器函數(shù),'Sthtodo'
是過濾器函數(shù)的參數(shù),整體的含義是在沒有聲明head_title
變量值或者head_title
變量值為空值或False
或0
時,默認(rèn)值為'Sthtodo'
。
我們所有頁面的前端框架引用開源的Bootstrap(3.3.7)和jQuery(1.12.4),Bootstrap的語法可參考getbootstrap官網(wǎng),jQuery的語法可參考W3school。
創(chuàng)建繼承模版index.html
和note.html
,然后添加代碼
$ touch templates/index.html
{% extends "base.html" %}
{% block main_body %}
<div class="home-page">
<div class="container text-center">
<h1>{{ body_title }}</h1>
<p><a href="/note/">Go to note</a></p>
</div>
</div>
{% endblock %}
$ touch templates/note.html
{% extends "base.html" %}
{% block main_body %}
<div class="note-page">
<div class="container text-center">
<h1>{{ body_title }}</h1>
<p><a href="/">Back home</a></p>
</div>
</div>
{% endblock %}
對于繼承模板,使用{% extends %}
標(biāo)簽來繼承通用模板base.html
,然后在名為main_body
的{% block %}
標(biāo)簽下重載不同的內(nèi)容,最終在繼承的通用模板base.html
中替換掉同樣名為main_body
的{% block %}
標(biāo)簽下的內(nèi)容。
現(xiàn)在模板的配置和添加完畢,用Git提交修改
(sthtodo) vagrant@precise64:~/sthtodo$ git status
On branch config
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: sthtodo/settings.py
Untracked files:
(use "git add <file>..." to include in what will be committed)
templates/
no changes added to commit (use "git add" and/or "git commit -a")
(sthtodo) vagrant@precise64:~/sthtodo$ git add -A
(sthtodo) vagrant@precise64:~/sthtodo$ git commit -m "Create and config templates"
[config 5387939] Create and config templates
5 files changed, 45 insertions(+), 1 deletion(-)
create mode 100644 templates/base.html
create mode 100644 templates/head.html
create mode 100644 templates/index.html
create mode 100644 templates/note.html
(sthtodo) Mengxuns-MacBook-Air:sthtodo harry_hmx$ git push origin config
Counting objects: 9, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (9/9), done.
Writing objects: 100% (9/9), 1.21 KiB | 617.00 KiB/s, done.
Total 9 (delta 4), reused 0 (delta 0)
remote: Resolving deltas: 100% (4/4), completed with 3 local objects.
To github.com:harryhmx/sthtodo.git
6419421..5387939 config -> config
視圖和網(wǎng)址(View & URL)
有了模板文件,還要結(jié)合視圖和網(wǎng)址才能展示頁面內(nèi)容給用戶,其中視圖的作用是后端邏輯,通過定義視圖函數(shù)調(diào)用相應(yīng)的模板文件,而網(wǎng)址通過URL配置文件(分發(fā)器)關(guān)聯(lián)視圖函數(shù),最終通過直接輸入網(wǎng)址來展示頁面內(nèi)容。
定義視圖函數(shù)
打開子目錄home
下的視圖文件views.py
,添加代碼 (如果沒有就創(chuàng)建一個,以下同理)
# -*- coding: utf-8 -*-
from django.shortcuts import render
def index(request):
print('{}: Request Home Page!'.format(request.get_host()))
return render(request, 'index.html', {'body_title': 'Home Page'})
在該視圖index
函數(shù)中,我們向服務(wù)器輸出包含當(dāng)前主機(jī)名和Request Home Page
的一段文字,最后的返回值操作調(diào)用模板文件index.html
并用render()
方法渲染模板。
而字典類型的值{'body_title': 'Home Page'}
做為參數(shù)傳遞到模板文件index.html
,這時模板中的變量{{ body_title }}
對應(yīng)參數(shù)值中的'body_title'
,同時參數(shù)值中'body_title'
關(guān)聯(lián)值'Home Page'
,這樣模版中的變量{{ body_title }}
就被值'Home Page'
所覆蓋。
接著再打開另一個視圖文件note/views.py
,添加代碼
# -*- coding: utf-8 -*-
from django.shortcuts import render
def index(request):
print('{}: Request Note Page!'.format(request.get_host()))
return render(request, 'note.html', {'head_title': 'Sthtodo Note', 'body_title': 'Note Page'})
網(wǎng)址配置
完成視圖函數(shù)的定義,最后一步就是網(wǎng)址配置。打開子目錄sthtodo
下的URL配置文件urls.py
,首先引入模塊如下
from django.conf.urls import url
from django.contrib import admin
from home import views as hv # New
from note import views as nv # New
然后在變量urlpatterns
中添加如下
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', hv.index, name='home'), # New
url(r'^note/$', nv.index, name='note'), # New
]
現(xiàn)在再次啟動開發(fā)服務(wù)器,運(yùn)行項目
$ python manage.py runserver
(sthtodo) vagrant@precise64:~/sthtodo$ python manage.py runserver
Performing system checks...
System check identified no issues (0 silenced).
You have 13 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
February 18, 2019 - 16:18:52
Django version 1.11.8, using settings 'sthtodo.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
localhost:8000: Request Home Page!
[18/Feb/2019 16:18:57] "GET / HTTP/1.1" 200 855
localhost:8000: Request Note Page!
[18/Feb/2019 16:19:06] "GET /note/ HTTP/1.1" 200 854
這樣,一個最簡單的自定義網(wǎng)站大功告成。
接下來用Git提交修改,合并config
分支
(sthtodo) vagrant@precise64:~/sthtodo$ git status
On branch config
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: home/views.py
modified: note/views.py
modified: sthtodo/urls.py
no changes added to commit (use "git add" and/or "git commit -a")
(sthtodo) vagrant@precise64:~/sthtodo$ git add -A
(sthtodo) vagrant@precise64:~/sthtodo$ git commit -m "Config views & urls"
[config 9dea3e3] Config views & urls
3 files changed, 12 insertions(+), 2 deletions(-)
(sthtodo) vagrant@precise64:~/sthtodo$ git push origin config
Counting objects: 8, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (8/8), done.
Writing objects: 100% (8/8), 868 bytes | 868.00 KiB/s, done.
Total 8 (delta 6), reused 0 (delta 0)
remote: Resolving deltas: 100% (6/6), completed with 5 local objects.
To github.com:harryhmx/sthtodo.git
5387939..9dea3e3 config -> config
最后在本地倉庫切換回master
主分支,并更新修改
(sthtodo) vagrant@precise64:~/sthtodo$ git checkout master
Switched to branch 'master'
Your branch is up to date with 'origin/master'.
(sthtodo) vagrant@precise64:~/sthtodo$ git pull origin master
Warning: Permanently added the RSA host key for IP address '13.229.188.59' to the list of known hosts.
remote: Enumerating objects: 1, done.
remote: Counting objects: 100% (1/1), done.
remote: Total 1 (delta 0), reused 0 (delta 0), pack-reused 0
Unpacking objects: 100% (1/1), done.
From github.com:harryhmx/sthtodo
* branch master -> FETCH_HEAD
74adfd2..c4f8f1f master -> origin/master
Updating 74adfd2..c4f8f1f
Fast-forward
home/__init__.py | 0
home/admin.py | 3 +++
home/apps.py | 5 +++++
home/migrations/__init__.py | 0
home/models.py | 3 +++
home/tests.py | 3 +++
home/views.py | 6 ++++++
note/__init__.py | 0
note/admin.py | 3 +++
note/apps.py | 5 +++++
note/migrations/__init__.py | 0
note/models.py | 3 +++
note/tests.py | 3 +++
note/views.py | 6 ++++++
sthtodo/settings.py | 4 +++-
sthtodo/urls.py | 4 ++++
templates/base.html | 10 ++++++++++
templates/head.html | 12 ++++++++++++
templates/index.html | 10 ++++++++++
templates/note.html | 10 ++++++++++
20 files changed, 89 insertions(+), 1 deletion(-)
create mode 100644 home/__init__.py
create mode 100644 home/admin.py
create mode 100644 home/apps.py
create mode 100644 home/migrations/__init__.py
create mode 100644 home/models.py
create mode 100644 home/tests.py
create mode 100644 home/views.py
create mode 100644 note/__init__.py
create mode 100644 note/admin.py
create mode 100644 note/apps.py
create mode 100644 note/migrations/__init__.py
create mode 100644 note/models.py
create mode 100644 note/tests.py
create mode 100644 note/views.py
create mode 100644 templates/base.html
create mode 100644 templates/head.html
create mode 100644 templates/index.html
create mode 100644 templates/note.html
至此,完成了自定義網(wǎng)站最簡單最基本的配置。
下一章節(jié),配置靜態(tài)文件和模型,未完待續(xù) ...