1. 程式人生 > >《Django Girls》學習筆記(1)

《Django Girls》學習筆記(1)

Need help? Talk to us!

Django Girls Tutorial

介紹

安裝

網際網路是如何工作的?

命令列介紹

Python的安裝

程式碼編輯器

Python 簡介

Django 是什麼?

Django安裝

你的第一個Django 專案 !

在蘋果或Linux系統下,你需要執行下面的命令,記得不要漏掉命令後面的小點(.):

(myvenv) ~/djangogirls$ django-admin startproject mysite .

(myvenv) ~/djangogirls$ 
django-admin startproject mysite .

更改設定

讓我們在 mysite/settings.py 中進行一些更改。使用您前面安裝了的程式碼編輯器開啟檔案。

在我們的站點上有正確的時間是非常不錯的。 訪問wikipedia timezones list複製你所在地區的時區 (TZ).

然後在 settings.py檔案中, 找到包含TIME_ZONE欄位的這行,並將時區改為你所在地區的時區。即:

python
TIME_ZONE = ‘Asia/Shanghai’

中國大陸地區可修改為 Asia/Shanghai
我們還需要新增 (我們會找出在教程後面所提到的靜態檔案和 CSS檔案) 靜態檔案的路徑。 我們下拉到檔案的最底部, 就是在

STATIC_URL條目的下面。新增新的一行內容為STATIC_ROOT`:

STATIC_URL = '/static/'

STATIC_ROOT = os.path.join(BASE_DIR, 'static')

Django模型

Django管理

為了登入, 你需要建立一個掌控整個網站所有東西的超級使用者。 回到剛才的命令列,輸入python manage.py createsuperuser,按下Enter。 然後輸入你的使用者名稱(英文小寫,不包括空格), 郵箱和密碼。 你輸密碼的時候看不見輸入?別擔心,它就是這樣的。 你就輸入要輸得到然後按Enter繼續就好了。 輸出應該長得像這樣(使用者名稱和郵箱應該是你自己的):

(myvenv) ~/djangogirls$ python manage.py createsuperuser
Username: admin_henry
Email address: 我的 秋秋 郵箱
Password: 我的姓名拼音 + XX 手機號
Password (again):
Superuser created successfully.

部署!

在 PythonAnywhere 上建立 virtualenv

如同你在自己電腦上做的,你可以在 PythonAnywhere 上建立 virtualenv 虛擬環境。在 Bash 控制檯下,鍵入:

$ cd my-first-blog

$ virtualenv --python=python3.4 myvenv
Running virtualenv with interpreter /usr/bin/python3.4
[...]
Installing setuptools, pip...done.

$ source myvenv/bin/activate

(mvenv) $  pip install django whitenoise
Collecting django
[...]
Successfully installed django-1.8.2 whitenoise-2.0

(建議:上一步在安裝Django時,最好安裝與教程相同的版本,pip install django==1.8 或 1.8.2 ,否則,後續可能出現一些錯誤,而且修復起來略麻煩。)
注意 pip 安裝 步驟可能需要幾分鐘。 耐心,耐心!但是如果超過 5 分鐘,就不對勁了。 問問你的教練。

在 PythonAnywhere 上建立資料庫

伺服器與你自己的計算機不同的另外一點是:它使用不同的資料庫。因此使用者賬戶以及文章和你電腦上的可能會有不同。

我們可以像在自己的計算機上一樣在伺服器上初始化資料庫,使用 migrate 以及 createsuperuser:

(mvenv) $ python manage.py migrate
Operations to perform:
[...]
  Applying sessions.0001_initial... OK

(如果

在 PythonAnywhere 上建立 virtualenv

中,安裝的django的版本就是1.8的話,那麼,下面的2處bug可能不會出現,應該也不用看了。)
(在做到這一步的時候,會報錯
(myvenv) 09:23 ~/django_girls_learning (master)$ python manage.py migrate
Traceback (most recent call last):
  File "/home/henry1991/django_girls_learning/myvenv/lib/python3.4/site-packages/django/urls/co
nf.py", line 17, in include
    urlconf_module, app_name = arg
ValueError: too many values to unpack (expected 2)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/home/henry1991/django_girls_learning/myvenv/lib/python3.4/site-packages/django/core/ma
nagement/__init__.py", line 371, in execute_from_command_line
    utility.execute()
  File "/home/henry1991/django_girls_learning/myvenv/lib/python3.4/site-packages/django/core/ma
nagement/__init__.py", line 365, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/henry1991/django_girls_learning/myvenv/lib/python3.4/site-packages/django/core/ma
nagement/base.py", line 288, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/henry1991/django_girls_learning/myvenv/lib/python3.4/site-packages/django/core/ma
nagement/base.py", line 332, in execute
    self.check()
  File "/home/henry1991/django_girls_learning/myvenv/lib/python3.4/site-packages/django/core/ma
nagement/base.py", line 364, in check
    include_deployment_checks=include_deployment_checks,
  File "/home/henry1991/django_girls_learning/myvenv/lib/python3.4/site-packages/django/core/ma
nagement/commands/migrate.py", line 58, in _run_checks
    issues.extend(super()._run_checks(**kwargs))
  File "/home/henry1991/django_girls_learning/myvenv/lib/python3.4/site-packages/django/core/ma
nagement/base.py", line 351, in _run_checks
    return checks.run_checks(**kwargs)
  File "/home/henry1991/django_girls_learning/myvenv/lib/python3.4/site-packages/django/core/ch
ecks/registry.py", line 73, in run_checks
    new_errors = check(app_configs=app_configs)
  File "/home/henry1991/django_girls_learning/myvenv/lib/python3.4/site-packages/django/core/ch
ecks/urls.py", line 13, in check_url_config
    return check_resolver(resolver)
  File "/home/henry1991/django_girls_learning/myvenv/lib/python3.4/site-packages/django/core/ch
ecks/urls.py", line 23, in check_resolver
    return check_method()
  File "/home/henry1991/django_girls_learning/myvenv/lib/python3.4/site-packages/django/urls/re
solvers.py", line 399, in check
    for pattern in self.url_patterns:
  File "/home/henry1991/django_girls_learning/myvenv/lib/python3.4/site-packages/django/utils/f
unctional.py", line 36, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/henry1991/django_girls_learning/myvenv/lib/python3.4/site-packages/django/urls/re
solvers.py", line 540, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/home/henry1991/django_girls_learning/myvenv/lib/python3.4/site-packages/django/utils/f
unctional.py", line 36, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/henry1991/django_girls_learning/myvenv/lib/python3.4/site-packages/django/urls/re
solvers.py", line 533, in urlconf_module
    return import_module(self.urlconf_name)
  File "/home/henry1991/django_girls_learning/myvenv/lib/python3.4/importlib/__init__.py", line
 109, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 2254, in _gcd_import
  File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
  File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 1129, in _exec
  File "<frozen importlib._bootstrap>", line 1471, in exec_module
  File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed
  File "/home/henry1991/django_girls_learning/mysite/urls.py", line 9, in <module>
    url(r'^admin/', include(admin.site.urls)),
  File "/home/henry1991/django_girls_learning/myvenv/lib/python3.4/site-packages/django/urls/co
nf.py", line 27, in include
    'provide the namespace argument to include() instead.' % len(arg)
django.core.exceptions.ImproperlyConfigured: Passing a 3-tuple to include() is not supported. P
ass a 2-tuple containing the list of patterns and app_name, and provide the namespace argument 
to include() instead.

特別要注意這裡 File "/home/henry1991/django_girls_learning/mysite/urls.py", line 9, in <module>
url(r'^admin/', include(admin.site.urls)),

將 mysite 下的 urls.py 的第 9 行url(r'^admin/', include(admin.site.urls)) 修改為 url(r'^admin/', admin.site.urls) ,就修復了這個 bug 。

但是,此時(myvenv) 09:40 ~/django_girls_learning (master)$ python manage.py migrate會有另外 1 個bug:

(myvenv) 09:40 ~/django_girls_learning (master)$ python manage.py migrate                      
Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/home/henry1991/django_girls_learning/myvenv/lib/python3.4/site-packages/django/core/ma
nagement/__init__.py", line 371, in execute_from_command_line
    utility.execute()
  File "/home/henry1991/django_girls_learning/myvenv/lib/python3.4/site-packages/django/core/ma
nagement/__init__.py", line 365, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/henry1991/django_girls_learning/myvenv/lib/python3.4/site-packages/django/core/ma
nagement/base.py", line 288, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/henry1991/django_girls_learning/myvenv/lib/python3.4/site-packages/django/core/ma
nagement/base.py", line 335, in execute
    output = self.handle(*args, **options)
  File "/home/henry1991/django_girls_learning/myvenv/lib/python3.4/site-packages/django/core/ma
nagement/commands/migrate.py", line 79, in handle
    executor = MigrationExecutor(connection, self.migration_progress_callback)
  File "/home/henry1991/django_girls_learning/myvenv/lib/python3.4/site-packages/django/db/migr
ations/executor.py", line 18, in __init__
    self.loader = MigrationLoader(self.connection)
  File "/home/henry1991/django_girls_learning/myvenv/lib/python3.4/site-packages/django/db/migr
ations/loader.py", line 49, in __init__
    self.build_graph()
  File "/home/henry1991/django_girls_learning/myvenv/lib/python3.4/site-packages/django/db/migr
ations/loader.py", line 201, in build_graph
    self.load_disk()
  File "/home/henry1991/django_girls_learning/myvenv/lib/python3.4/site-packages/django/db/migr
ations/loader.py", line 110, in load_disk
    migration_module = import_module("%s.%s" % (module_name, migration_name))
  File "/home/henry1991/django_girls_learning/myvenv/lib/python3.4/importlib/__init__.py", line
 109, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 2254, in _gcd_import
  File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
  File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 1129, in _exec
  File "<frozen importlib._bootstrap>", line 1471, in exec_module
  File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed
  File "/home/henry1991/django_girls_learning/blog/migrations/0001_initial.py", line 9, in <mod
ule>
    class Migration(migrations.Migration):
  File "/home/henry1991/django_girls_learning/blog/migrations/0001_initial.py", line 24, in Mig
ration
    ('author', models.ForeignKey(to=settings.AUTH_USER_MODEL)),
TypeError: __init__() missing 1 required positional argument: 'on_delete'

特別要注意這裡

File "/home/henry1991/django_girls_learning/blog/migrations/0001_initial.py", line 24, in Mig
ration
    ('author', models.ForeignKey(to=settings.AUTH_USER_MODEL)),
TypeError: __init__() missing 1 required positional argument: 'on_delete'

根據搜尋到的解決辦法 https://www.cnblogs.com/phyger/p/8035253.html ,將 /blog/migrations/ 下的 0001_initial.py 的 第 24 行的 ('author', models.ForeignKey(to=settings.AUTH_USER_MODEL)) 加上 on_delete ,即修改為

('author', models.ForeignKey(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE)),

至此,修復完畢。
)

(mvenv) $ python manage.py createsuperuser

Context | Request Context

配置 WSGI 檔案

Django 使用 “WSGI 協議”,它是用來服務 Python 網站的一個標準。PythonAnywhere 支援這個標準。 PythonAnywhere 識別我們 Django 部落格的方式是通過配置 WSGI 配置檔案。

點選 “WSGI configuration file” 連結(在 “Code” 一節,接近頁面上方 — 它將被命名為如 /var/www/_pythonanywhere_com_wsgi.py),然後跳轉到一個編輯器。

刪除所有的內容並用以下內容替換:

import os
import sys

path = '/home/<你的使用者名稱>/my-first-blog'  # use your own username here
if path not in sys.path:
    sys.path.append(path)

os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'

from django.core.wsgi import get_wsgi_application
from whitenoise.django import DjangoWhiteNoise
application = DjangoWhiteNoise(get_wsgi_application())

注意 當看到 時,別忘了替換為你自己的使用者名稱。(這裡要特別注意,不然會出錯。)

這個檔案的作用是告訴 PythonAnywhere 我們的Web應用程式在什麼位置,Django 設定檔案的名字是什麼。它也設定 “whitenoise” 靜態檔案工具。

點選 Save 然後返回到 Web 選項卡。

一切搞定!點選大大的綠色 Reload 按鈕然後你將會看到你的應用程式。頁面的頂部可以看到它的連結。

Django urls

Django檢視 - 抓緊時間去建立!

HTML簡介

Django ORM (查詢集)

模板中的動態資料

Django模板

CSS - 讓其更漂亮

模板擴充套件

擴充套件您的應用

Django表單

接下來呢?

本書使用 GitBook 釋出