【ログ】Ubuntu 20.04: apt list --upgradable

  • 実行コマンド:apt list --upgradable
  • 実行日 2021/04/09
  • 実行環境:Ubuntu 20.04
ubuntu@xx1-234-56789:~$ apt list --upgradable
Listing... Done
accountsservice/focal-updates 0.6.55-0ubuntu12~20.04.2 amd64 [upgradable from: 0.6.55-0ubuntu12~20.04.1]
alsa-ucm-conf/focal-updates 1.2.2-1ubuntu0.4 all [upgradable from: 1.2.2-1ubuntu0.1]
apport/focal-updates 2.20.11-0ubuntu27.10 all [upgradable from: 2.20.11-0ubuntu27.6]
base-files/focal-updates 11ubuntu5.2 amd64 [upgradable from: 11ubuntu5.1]
bcache-tools/focal-updates 1.0.8-3ubuntu0.1 amd64 [upgradable from: 1.0.8-3]
bind9-dnsutils/focal-updates 1:9.16.1-0ubuntu2.4 amd64 [upgradable from: 1:9.16.1-0ubuntu2.3]
bind9-host/focal-updates 1:9.16.1-0ubuntu2.4 amd64 [upgradable from: 1:9.16.1-0ubuntu2.3]
bind9-libs/focal-updates 1:9.16.1-0ubuntu2.4 amd64 [upgradable from: 1:9.16.1-0ubuntu2.3]
bolt/focal-updates 0.8-4ubuntu1 amd64 [upgradable from: 0.8-4]
bsdutils/focal-updates 1:2.34-0.1ubuntu9.1 amd64 [upgradable from: 1:2.34-0.1ubuntu9]
command-not-found/focal-updates 20.04.4 all [upgradable from: 20.04.2]
cryptsetup-bin/focal-updates 2:2.2.2-3ubuntu2.3 amd64 [upgradable from: 2:2.2.2-3ubuntu2.2]
cryptsetup-initramfs/focal-updates 2:2.2.2-3ubuntu2.3 all [upgradable from: 2:2.2.2-3ubuntu2.2]
cryptsetup-run/focal-updates 2:2.2.2-3ubuntu2.3 all [upgradable from: 2:2.2.2-3ubuntu2.2]
cryptsetup/focal-updates 2:2.2.2-3ubuntu2.3 amd64 [upgradable from: 2:2.2.2-3ubuntu2.2]
fdisk/focal-updates 2.34-0.1ubuntu9.1 amd64 [upgradable from: 2.34-0.1ubuntu9]
finalrd/focal-updates 6~ubuntu20.04.1 all [upgradable from: 5]
initramfs-tools-bin/focal-updates 0.136ubuntu6.3 amd64 [upgradable from: 0.136ubuntu6.2]
initramfs-tools-core/focal-updates 0.136ubuntu6.3 all [upgradable from: 0.136ubuntu6.2]
initramfs-tools/focal-updates 0.136ubuntu6.3 all [upgradable from: 0.136ubuntu6.2]
language-selector-common/focal-updates 0.204.2 all [upgradable from: 0.204]
libaccountsservice0/focal-updates 0.6.55-0ubuntu12~20.04.2 amd64 [upgradable from: 0.6.55-0ubuntu12~20.04.1]
libasound2-data/focal-updates 1.2.2-2.1ubuntu2 all [upgradable from: 1.2.2-2.1ubuntu1]
libasound2/focal-updates 1.2.2-2.1ubuntu2 amd64 [upgradable from: 1.2.2-2.1ubuntu1]
libblkid1/focal-updates 2.34-0.1ubuntu9.1 amd64 [upgradable from: 2.34-0.1ubuntu9]
libc-bin/focal-updates 2.31-0ubuntu9.1 amd64 [upgradable from: 2.31-0ubuntu9]
libc6/focal-updates 2.31-0ubuntu9.1 amd64 [upgradable from: 2.31-0ubuntu9]
libcryptsetup12/focal-updates 2:2.2.2-3ubuntu2.3 amd64 [upgradable from: 2:2.2.2-3ubuntu2.2]
libdns-export1109/focal-updates 1:9.11.16+dfsg-3~ubuntu1 amd64 [upgradable from: 1:9.11.16+dfsg-3~build1]
libfdisk1/focal-updates 2.34-0.1ubuntu9.1 amd64 [upgradable from: 2.34-0.1ubuntu9]
libisc-export1105/focal-updates 1:9.11.16+dfsg-3~ubuntu1 amd64 [upgradable from: 1:9.11.16+dfsg-3~build1]
liblzma5/focal-updates 5.2.4-1ubuntu1 amd64 [upgradable from: 5.2.4-1]
libmount1/focal-updates 2.34-0.1ubuntu9.1 amd64 [upgradable from: 2.34-0.1ubuntu9]
libnetplan0/focal-updates 0.100-0ubuntu4~20.04.2 amd64 [upgradable from: 0.99-0ubuntu3~20.04.2]
libpam-modules-bin/focal-updates 1.3.1-5ubuntu4.1 amd64 [upgradable from: 1.3.1-5ubuntu4]
libpam-modules/focal-updates 1.3.1-5ubuntu4.1 amd64 [upgradable from: 1.3.1-5ubuntu4]
libpam-runtime/focal-updates 1.3.1-5ubuntu4.1 all [upgradable from: 1.3.1-5ubuntu4]
libpam0g/focal-updates 1.3.1-5ubuntu4.1 amd64 [upgradable from: 1.3.1-5ubuntu4]
libplymouth5/focal-updates 0.9.4git20200323-0ubuntu6.1 amd64 [upgradable from: 0.9.4git20200323-0ubuntu6]
libsmartcols1/focal-updates 2.34-0.1ubuntu9.1 amd64 [upgradable from: 2.34-0.1ubuntu9]
libuuid1/focal-updates 2.34-0.1ubuntu9.1 amd64 [upgradable from: 2.34-0.1ubuntu9]
locales/focal-updates 2.31-0ubuntu9.1 all [upgradable from: 2.31-0ubuntu9]
mdadm/focal-updates 4.1-5ubuntu1.2 amd64 [upgradable from: 4.1-5ubuntu1]
mount/focal-updates 2.34-0.1ubuntu9.1 amd64 [upgradable from: 2.34-0.1ubuntu9]
netplan.io/focal-updates 0.100-0ubuntu4~20.04.2 amd64 [upgradable from: 0.99-0ubuntu3~20.04.2]
open-vm-tools/focal-updates 2:11.1.5-1~ubuntu20.04.2 amd64 [upgradable from: 2:11.0.5-4]
plymouth-theme-ubuntu-text/focal-updates 0.9.4git20200323-0ubuntu6.1 amd64 [upgradable from: 0.9.4git20200323-0ubuntu6]
plymouth/focal-updates 0.9.4git20200323-0ubuntu6.1 amd64 [upgradable from: 0.9.4git20200323-0ubuntu6]
python3-apport/focal-updates 2.20.11-0ubuntu27.10 all [upgradable from: 2.20.11-0ubuntu27.6]
python3-commandnotfound/focal-updates 20.04.4 all [upgradable from: 20.04.2]
python3-distupgrade/focal-updates 1:20.04.28 all [upgradable from: 1:20.04.23]
python3-problem-report/focal-updates 2.20.11-0ubuntu27.10 all [upgradable from: 2.20.11-0ubuntu27.6]
rsyslog/focal-updates 8.2001.0-1ubuntu1.1 amd64 [upgradable from: 8.2001.0-1ubuntu1]
sosreport/focal-updates 4.0-1~ubuntu0.20.04.2 amd64 [upgradable from: 3.9.1-1ubuntu0.20.04.2]
sudo/focal-updates 1.8.31-1ubuntu1.1 amd64 [upgradable from: 1.8.31-1ubuntu1]
tmux/focal-updates 3.0a-2ubuntu0.1 amd64 [upgradable from: 3.0a-2]
ubuntu-minimal/focal-updates 1.450.2 amd64 [upgradable from: 1.450.1]
ubuntu-release-upgrader-core/focal-updates 1:20.04.28 all [upgradable from: 1:20.04.23]
ubuntu-server/focal-updates 1.450.2 amd64 [upgradable from: 1.450.1]
ubuntu-standard/focal-updates 1.450.2 amd64 [upgradable from: 1.450.1]
unattended-upgrades/focal-updates 2.3ubuntu0.1 all [upgradable from: 2.3]
util-linux/focal-updates 2.34-0.1ubuntu9.1 amd64 [upgradable from: 2.34-0.1ubuntu9]
uuid-runtime/focal-updates 2.34-0.1ubuntu9.1 amd64 [upgradable from: 2.34-0.1ubuntu9]
xz-utils/focal-updates 5.2.4-1ubuntu1 amd64 [upgradable from: 5.2.4-1]
zlib1g/focal-updates 1:1.2.11.dfsg-2ubuntu1.1 amd64 [upgradable from: 1:1.2.11.dfsg-2ubuntu1]
ubuntu@xx1-234-56789:~$ 

【Ubuntu】sudo ユーザーを作成する方法

ユーザーの作成

root ユーザーに昇格します。

ubuntu@xx1-234-56789:~$ sudo su -

「adduser ユーザー名」でユーザーを作成します。

root@xx1-234-56789:~# adduser adminvps
Adding user `adminvps' ...
Adding new group `adminvps' (1002) ...
Adding new user `adminvps' (1002) with group `adminvps' ...
Creating home directory `/home/adminvps' ...
Copying files from `/etc/skel' ...
New password: 
Retype new password: 
passwd: password updated successfully
Changing the user information for adminvps
Enter the new value, or press ENTER for the default
	Full Name []: 
	Room Number []: 
	Work Phone []: 
	Home Phone []: 
	Other []: 
Is the information correct? [Y/n] Y
root@xx1-234-56789:~#

sudo グループに追加

このユーザーで sudo コマンドが使える様、sudo グループに追加します。

root@xx1-234-56789:~# gpasswd -a adminvps sudo
Adding user adminvps to group sudo
root@xx1-234-56789:~#

「exit」で root から出ます。

root@xx1-234-56789:~# exit
logout
ubuntu@xx1-234-56789:~$

今追加したユーザーで接続してみます。質問に「yes」と回答してパスワードを入力すると無事新ユーザーで接続ができます。

ubuntu@xx1-234-56789:~$ ssh adminvps@xx1-234-56789.vs.sakura.ne.jp
The authenticity of host '@xx1-234-56789 (127.0.1.1)' can't be established.
ECDSA key fingerprint is QWE123:QWERTYUIOPASD+QWERTYUIOP+ZXCVBNM.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added 'xx1-234-56789' (ECDSA) to the list of known hosts.
adminvps@xx1-234-56789's password: 
Welcome to Ubuntu 20.04.2 LTS (GNU/Linux 5.4.0-70-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Fri Apr  9 19:43:32 JST 2021

  System load:  0.0               Processes:             119
  Usage of /:   2.6% of 94.43GB   Users logged in:       1
  Memory usage: 18%               IPv4 address for ens3: 133.125.39.81
  Swap usage:   0%

 * Introducing self-healing high availability clusters in MicroK8s.
   Simple, hardened, Kubernetes for production, from RaspberryPi to DC.

     https://microk8s.io/high-availability

0 updates can be installed immediately.
0 of these updates are security updates.



The programs included with the Ubuntu system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
applicable law.


SAKURA internet [Virtual Private Server SERVICE]

To run a command as administrator (user "root"), use "sudo <command>".
See "man sudo_root" for details.

adminvps@xx1-234-56789:~$ 

【2021年4月〜6月】YouTube 急上昇入りランキング

2021 年第 2 四半期の YouTube 急上昇動画数をチャンネル別にランキング形式で掲載しています。

チャンネル名ランクイン動画数
東海オンエア41 動画
ジャにのちゃんねる20 動画
Fischer's-フィッシャーズ-13 動画
MLB11 動画
NiziU Official10 動画
もちまる日記10 動画
P丸様。9 動画
コムドット9 動画
SixTONES9 動画
はじめしゃちょー(hajime)9 動画
両学長 リベラルアーツ大学9 動画
48-フォーエイト9 動画
THE FIRST TAKE9 動画
バンカラジオ8 動画
パパラピーズ8 動画
ジャニーズJr.チャンネル8 動画
SMTOWN8 動画
はじめまして松尾です8 動画
日向坂46 OFFICIAL YouTube CHANNEL8 動画
朝倉未来 Mikuru Asakura8 動画
仲里依紗です。7 動画
坂上家のチャンネル7 動画
エミリンチャンネル7 動画
すとぷりちゃんねる7 動画
Nintendo 公式チャンネル7 動画
BANGTANTV7 動画
TBS NEWS7 動画
あきひら。7 動画
きまぐれクックKimagure Cook7 動画
佐賀よかでしょう。7 動画
テイコウペンギン6 動画
東映特撮YouTube Official6 動画
HYBE LABELS6 動画
kemio6 動画
さしはらちゃんねる6 動画
阪神タイガース 公式6 動画
Snow Man6 動画
ヴァンゆんチャンネル【VAMYUN】6 動画
貴ちゃんねるず6 動画
とうあ6 動画
SATAbuilder's6 動画
スカイピースの平和島6 動画
TWICE JAPAN OFFICIAL YouTube Channel6 動画
JO16 動画
あめんぼぷらす【日常コメディ】6 動画
CapcomChannel6 動画
TOP4切り抜きチャンネル【公式】6 動画
RIZIN FIGHTING FEDERATION6 動画
アドレナリン チャンネル6 動画
Naokiman 2nd Channel5 動画

Python の YouTube Data API v3 でチャンネル・動画情報を取得する方法

YouTube Data API v3 では、YouTube 上の様々な情報を取得する事ができます。こちらの記事では API キーの作成からチャンネル、動画情報の取得までを解説します。

  1. API キーの作成
  2. ライブラリのインストール
  3. API リクエストを試してみる
  4. 取得できる情報

1. API キーの作成

「認証情報」のタブを開きます。

「+認証情報を作成」をクリックし「API キー」を選択。

黒く塗りつぶしてますが、ここに API キーが表示されます。

2. ライブラリのインストール

仮想環境内で Google APIs Client Library for Python をインストールします。

コマンド「pip install --upgrade google-api-python-client」を実行します。

(sample_venv) % pip install --upgrade google-api-python-client
Collecting google-api-python-client
  Downloading https://files.pythonhosted.org/packages/b7/56/bc7314cd180d1420e4ef11202dc9548ec22237a0a6de1aaf37b460ee7753/google_api_python_client-2.0.2-py2.py3-none-any.whl (6.5MB)
     |████████████████████████████████| 6.5MB 9.0MB/s 
Collecting google-auth<2dev,>=1.16.0 (from google-api-python-client)
  Downloading https://files.pythonhosted.org/packages/b5/ef/13d3b65c41ddde1a57e89de6adfc610093d109ebd472545a33e76dcdd8bf/google_auth-1.28.0-py2.py3-none-any.whl (136kB)
     |████████████████████████████████| 143kB 10.8MB/s 
Collecting google-api-core<2dev,>=1.21.0 (from google-api-python-client)
  Downloading https://files.pythonhosted.org/packages/66/21/891884b4fe2eda194e5cdc9ea617b63ab41e0aca595c865492380e2c10b3/google_api_core-1.26.2-py2.py3-none-any.whl (93kB)
     |████████████████████████████████| 102kB 11.4MB/s 
Collecting httplib2<1dev,>=0.15.0 (from google-api-python-client)
  Downloading https://files.pythonhosted.org/packages/15/7e/51e5bd333c0afa1c7bdbf98eb3b0ccf5167e2b1ecc8b4d13e9cc29291f81/httplib2-0.19.0-py3-none-any.whl (95kB)
     |████████████████████████████████| 102kB 11.4MB/s 
Collecting uritemplate<4dev,>=3.0.0 (from google-api-python-client)
  Using cached https://files.pythonhosted.org/packages/bf/0c/60d82c077998feb631608dca3cc1fe19ac074e772bf0c24cf409b977b815/uritemplate-3.0.1-py2.py3-none-any.whl
Collecting google-auth-httplib2>=0.0.3 (from google-api-python-client)
  Downloading https://files.pythonhosted.org/packages/ba/db/721e2f3f32339080153995d16e46edc3a7657251f167ddcb9327e632783b/google_auth_httplib2-0.1.0-py2.py3-none-any.whl
Requirement already satisfied, skipping upgrade: six<2dev,>=1.13.0 in /Users/ユーザー名/PythonProjects/sample_venv/lib/python3.8/site-packages (from google-api-python-client) (1.15.0)
Collecting cachetools<5.0,>=2.0.0 (from google-auth<2dev,>=1.16.0->google-api-python-client)
  Downloading https://files.pythonhosted.org/packages/bb/72/8df2e0dc991f1a1d2c6869404e7622e8ee50d80bff357dbb57c3df70305b/cachetools-4.2.1-py3-none-any.whl
Collecting pyasn1-modules>=0.2.1 (from google-auth<2dev,>=1.16.0->google-api-python-client)
  Using cached https://files.pythonhosted.org/packages/95/de/214830a981892a3e286c3794f41ae67a4495df1108c3da8a9f62159b9a9d/pyasn1_modules-0.2.8-py2.py3-none-any.whl
Collecting rsa<5,>=3.1.4; python_version >= "3.6" (from google-auth<2dev,>=1.16.0->google-api-python-client)
  Downloading https://files.pythonhosted.org/packages/e9/93/0c0f002031f18b53af7a6166103c02b9c0667be528944137cc954ec921b3/rsa-4.7.2-py3-none-any.whl
Requirement already satisfied, skipping upgrade: setuptools>=40.3.0 in /Users/ユーザー名/PythonProjects/sample_venv/lib/python3.8/site-packages (from google-auth<2dev,>=1.16.0->google-api-python-client) (41.2.0)
Collecting packaging>=14.3 (from google-api-core<2dev,>=1.21.0->google-api-python-client)
  Downloading https://files.pythonhosted.org/packages/3e/89/7ea760b4daa42653ece2380531c90f64788d979110a2ab51049d92f408af/packaging-20.9-py2.py3-none-any.whl (40kB)
     |████████████████████████████████| 40kB 8.7MB/s 
Requirement already satisfied, skipping upgrade: requests<3.0.0dev,>=2.18.0 in /Users/ユーザー名/PythonProjects/sample_venv/lib/python3.8/site-packages (from google-api-core<2dev,>=1.21.0->google-api-python-client) (2.25.1)
Collecting googleapis-common-protos<2.0dev,>=1.6.0 (from google-api-core<2dev,>=1.21.0->google-api-python-client)
  Downloading https://files.pythonhosted.org/packages/55/08/796a6bc0b550e2b7116041c953d3d5100016abea106131d71e5651826e7b/googleapis_common_protos-1.53.0-py2.py3-none-any.whl (198kB)
     |████████████████████████████████| 204kB 11.0MB/s 
Collecting protobuf>=3.12.0 (from google-api-core<2dev,>=1.21.0->google-api-python-client)
  Downloading https://files.pythonhosted.org/packages/62/be/f610958bf64f2a64b6b0b3403d17564af53bbfad5dad69f69b164cca038d/protobuf-3.15.6-cp38-cp38-macosx_10_9_x86_64.whl (1.0MB)
     |████████████████████████████████| 1.0MB 10.8MB/s 
Requirement already satisfied, skipping upgrade: pytz in /Users/ユーザー名/PythonProjects/sample_venv/lib/python3.8/site-packages (from google-api-core<2dev,>=1.21.0->google-api-python-client) (2021.1)
Requirement already satisfied, skipping upgrade: pyparsing<3,>=2.4.2 in /Users/ユーザー名/PythonProjects/sample_venv/lib/python3.8/site-packages (from httplib2<1dev,>=0.15.0->google-api-python-client) (2.4.7)
Collecting pyasn1<0.5.0,>=0.4.6 (from pyasn1-modules>=0.2.1->google-auth<2dev,>=1.16.0->google-api-python-client)
  Using cached https://files.pythonhosted.org/packages/62/1e/a94a8d635fa3ce4cfc7f506003548d0a2447ae76fd5ca53932970fe3053f/pyasn1-0.4.8-py2.py3-none-any.whl
Requirement already satisfied, skipping upgrade: certifi>=2017.4.17 in /Users/ユーザー名/PythonProjects/sample_venv/lib/python3.8/site-packages (from requests<3.0.0dev,>=2.18.0->google-api-core<2dev,>=1.21.0->google-api-python-client) (2020.12.5)
Requirement already satisfied, skipping upgrade: chardet<5,>=3.0.2 in /Users/ユーザー名/PythonProjects/sample_venv/lib/python3.8/site-packages (from requests<3.0.0dev,>=2.18.0->google-api-core<2dev,>=1.21.0->google-api-python-client) (4.0.0)
Requirement already satisfied, skipping upgrade: urllib3<1.27,>=1.21.1 in /Users/ユーザー名/PythonProjects/sample_venv/lib/python3.8/site-packages (from requests<3.0.0dev,>=2.18.0->google-api-core<2dev,>=1.21.0->google-api-python-client) (1.26.4)
Requirement already satisfied, skipping upgrade: idna<3,>=2.5 in /Users/ユーザー名/PythonProjects/sample_venv/lib/python3.8/site-packages (from requests<3.0.0dev,>=2.18.0->google-api-core<2dev,>=1.21.0->google-api-python-client) (2.10)
Installing collected packages: cachetools, pyasn1, pyasn1-modules, rsa, google-auth, packaging, protobuf, googleapis-common-protos, google-api-core, httplib2, uritemplate, google-auth-httplib2, google-api-python-client
Successfully installed cachetools-4.2.1 google-api-core-1.26.2 google-api-python-client-2.0.2 google-auth-1.28.0 google-auth-httplib2-0.1.0 googleapis-common-protos-1.53.0 httplib2-0.19.0 packaging-20.9 protobuf-3.15.6 pyasn1-0.4.8 pyasn1-modules-0.2.8 rsa-4.7.2 uritemplate-3.0.1
(sample_venv) %

3. API リクエストを試してみる

まずはブラウザの URL バーから

まずは Python 関係なく、単純にブラウザの URL バーに下記の URL を入れてみます。(APIキーはご自分のを入れてください)

https://youtube.googleapis.com/youtube/v3/channels?part=snippet%2CcontentDetails%2Cstatistics&id=UC_x5XG1OV2P6uZZ5FSM9Ttw&key=APIキー

すると下記の JSON テキストが表示されました。ID「UC_x5XG1OV2P6uZZ5FSM9Ttw」の Google Developers チャンネルの情報が取れました。

Python での実行

同じことを Python でやろうとすると下記の様なコードになるそうです。(Google のサイト参照

import os

import googleapiclient.discovery

def main():
    # Disable OAuthlib's HTTPS verification when running locally.
    # *DO NOT* leave this option enabled in production.
    os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"

    api_service_name = "youtube"
    api_version = "v3"
    DEVELOPER_KEY = "API キー"

    youtube = googleapiclient.discovery.build(api_service_name, api_version, developerKey = DEVELOPER_KEY)

    request = youtube.channels().list( # channels().list
        part="snippet,contentDetails,statistics", # 取得したい情報の指定
        id="UC_x5XG1OV2P6uZZ5FSM9Ttw" # チャンネル ID を指定(複数も可)
    )
    response = request.execute()

    print(response)

if __name__ == "__main__":
    main()

「part」に渡しているのが取得するデータの種類です。この記事の最後に取得できる part のリストを載せておきます。

動画情報の場合は下記の通り。個人的に好きで見てた FF 7 リメイクのプレイ動画です。 動画ID「fdsaZ8EMR2U」で指定しています。

import os

import googleapiclient.discovery

def main():
    # Disable OAuthlib's HTTPS verification when running locally.
    # *DO NOT* leave this option enabled in production.
    os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"

    api_service_name = "youtube"
    api_version = "v3"
    DEVELOPER_KEY = "API キー"

    youtube = googleapiclient.discovery.build(
        api_service_name, api_version, developerKey = DEVELOPER_KEY)

    request = youtube.videos().list( # videos().list
        part="contentDetails", # 取得したい情報の指定
        id="fdsaZ8EMR2U" # 動画 ID を指定(複数も可)
    )
    response = request.execute()

    print(response)

if __name__ == "__main__":
    main()

動画情報の part の内下記は投稿主のみアクセスできるそうです。

  • fileDetails
  • processingDetails
  • suggestions

そして急上昇ランキングを取る場合はこう。動画 ID の指定は消して「chart="mostPopular"」、「regionCode="JP"」、「maxResults=50」 を追記します。

JP(日本)の mostPopular(急上昇ランキング)から 50 件のデータを取るという意味です。

import os

import googleapiclient.discovery

def main():
    # Disable OAuthlib's HTTPS verification when running locally.
    # *DO NOT* leave this option enabled in production.
    os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"

    api_service_name = "youtube"
    api_version = "v3"
    DEVELOPER_KEY = "API キー"

    youtube = googleapiclient.discovery.build(
        api_service_name, api_version, developerKey = DEVELOPER_KEY)

    request = youtube.videos().list(
        part="snippet,contentDetails,statistics", # 取得したい情報の指定
        chart="mostPopular", # chart に「mostPopular」を指定
        maxResults=50, # 最大件数
        regionCode="JP" # 地域コード
    )
    response = request.execute()

    print(response)

if __name__ == "__main__":
    main()

実行すると下記の様な内容の dict データが取れるはずです。(実際は整形されていない状態)

{
  "kind": "youtube#videoListResponse",
  "etag": "jUM1iWDvm5ncH7VdFCrks9TZYQY",
  "items": [
    {
      "kind": "youtube#video",
      "etag": "jtNs4gdyS4wCzxvZKpEA0GbXJ0M",
      "id": "GOBeIaj7Ml0",
      "snippet": {
        "publishedAt": "2021-03-27T11:00:43Z",
        "channelId": "UCpOjLndjOqMoffA-fr8cbKA",
        "title": "【コムドット】生意気な後輩YouTuberと学校貸し切って本気でドロケイした結果【アバ溜りドット】",
        "description": "まだまだ道は開けない!!\n\nアバンティーズ\nhttps://www.youtube.com/user/avntisdouga\n\nコムドット \nhttps://www.youtube.com/channel/UCRxPrFmRHsXGWfAyE6oqrPQ\n\nフォーエイト とのドロケイ動画はこちらです!\nhttps://youtu.be/cbrQUkl6iD8\n\n動画がいいなと思っていただけたら高評価押してください!再生数よりもこちらを参考にして動画を作りたい!!そして少しでも面白いなと思っていただけたらぜひ【チャンネル登録】お願いします!\n\n水溜りボンドLINE公式アカウント!\nhttps://lin.ee/cVkWzGW\n最新情報不定期配信中!僕らからのメッセージも届きますよ!\nぜひ友だち登録してください!\n\nしゃべる!水溜りボンドLINEスタンプ\nhttps://00m.in/AcJcI\n水溜りボンドLINEスタンプ\nhttps://00m.in/2mzGU\n水溜りボンドのグッズはこちら!\nhttps://muuu.com/users/c7bf52c2b9fb5c5a\nおすすめでございます!!\n\n6年間1度も休まず毎日投稿しておりました!これからも少しでもみなさんが楽しんでいただければ幸いです。\n\n\n\n☆水溜りボンドを初めて知った方に是非見ていただきたい動画はこちら!☆\nhttps://www.youtube.com/watch?v=BvRvt6Nxny8\n\n●水溜りボンドの日常!僕らのサブチャンネルです。毎日比較的ゆったりやってます〜\nhttps://www.youtube.com/channel/UCaTFX7ckdowpnwHWcJGH2KQ\n\n\n●水溜りボンドのオールナイトニッポン0の詳細はこちらから\nぜひフォローお願いいたします!!\nhttps://twitter.com/mizuann0\n●限定動画や専用の絵文字など。チャンネルメンバーシップはこちらから!\nhttps://www.youtube.com/channel/UCpOjLndjOqMoffA-fr8cbKA/join\n\n◆Twitter\nカンタのアカウント\nhttps://twitter.com/kantamizutamari\nトミーのアカウント\nhttps://twitter.com/miztamari_nikki\n\n■インスタグラム\nカンタのアカウント\nhttps://bit.ly/2UckzeP\nトミーのアカウント\nhttps://www.instagram.com/tommymizutamaribond/\nーーーーーー\nよく使用している友人のBGM作曲者さん↓\nhttps://twitter.com/gt_k_2014?lang=ja\n素材提供 Music-Note.jp(ミュージックノート)\n他の楽曲提供:Production Music by http://www.epidemicsound.com\n素材提供 PIXTA\n\n#水溜りボンド\n#ドロケイ\n#コムドット",
        "thumbnails": {
          "default": {
            "url": "https://i.ytimg.com/vi/GOBeIaj7Ml0/default.jpg",
            "width": 120,
            "height": 90
          },
          "medium": {
            "url": "https://i.ytimg.com/vi/GOBeIaj7Ml0/mqdefault.jpg",
            "width": 320,
            "height": 180
          },
          "high": {
            "url": "https://i.ytimg.com/vi/GOBeIaj7Ml0/hqdefault.jpg",
            "width": 480,
            "height": 360
          },
          "standard": {
            "url": "https://i.ytimg.com/vi/GOBeIaj7Ml0/sddefault.jpg",
            "width": 640,
            "height": 480
          },
          "maxres": {
            "url": "https://i.ytimg.com/vi/GOBeIaj7Ml0/maxresdefault.jpg",
            "width": 1280,
            "height": 720
          }
        },
        "channelTitle": "水溜りボンド",
        "tags": [
          "水溜りボンド",
          "都市伝説",
          "検証",
          "実験",
          "科学",
          "お笑い",
          "面白",
          "面白い",
          "企画",
          "楽しい",
          "ワクワク",
          "カンタ",
          "トミー"
        ],
        "categoryId": "24",
        "liveBroadcastContent": "none",
        "defaultLanguage": "ja",
        "localized": {
          "title": "【コムドット】生意気な後輩YouTuberと学校貸し切って本気でドロケイした結果【アバ溜りドット】",
          "description": "まだまだ道は開けない!!\n\nアバンティーズ\nhttps://www.youtube.com/user/avntisdouga\n\nコムドット \nhttps://www.youtube.com/channel/UCRxPrFmRHsXGWfAyE6oqrPQ\n\nフォーエイト とのドロケイ動画はこちらです!\nhttps://youtu.be/cbrQUkl6iD8\n\n動画がいいなと思っていただけたら高評価押してください!再生数よりもこちらを参考にして動画を作りたい!!そして少しでも面白いなと思っていただけたらぜひ【チャンネル登録】お願いします!\n\n水溜りボンドLINE公式アカウント!\nhttps://lin.ee/cVkWzGW\n最新情報不定期配信中!僕らからのメッセージも届きますよ!\nぜひ友だち登録してください!\n\nしゃべる!水溜りボンドLINEスタンプ\nhttps://00m.in/AcJcI\n水溜りボンドLINEスタンプ\nhttps://00m.in/2mzGU\n水溜りボンドのグッズはこちら!\nhttps://muuu.com/users/c7bf52c2b9fb5c5a\nおすすめでございます!!\n\n6年間1度も休まず毎日投稿しておりました!これからも少しでもみなさんが楽しんでいただければ幸いです。\n\n\n\n☆水溜りボンドを初めて知った方に是非見ていただきたい動画はこちら!☆\nhttps://www.youtube.com/watch?v=BvRvt6Nxny8\n\n●水溜りボンドの日常!僕らのサブチャンネルです。毎日比較的ゆったりやってます〜\nhttps://www.youtube.com/channel/UCaTFX7ckdowpnwHWcJGH2KQ\n\n\n●水溜りボンドのオールナイトニッポン0の詳細はこちらから\nぜひフォローお願いいたします!!\nhttps://twitter.com/mizuann0\n●限定動画や専用の絵文字など。チャンネルメンバーシップはこちらから!\nhttps://www.youtube.com/channel/UCpOjLndjOqMoffA-fr8cbKA/join\n\n◆Twitter\nカンタのアカウント\nhttps://twitter.com/kantamizutamari\nトミーのアカウント\nhttps://twitter.com/miztamari_nikki\n\n■インスタグラム\nカンタのアカウント\nhttps://bit.ly/2UckzeP\nトミーのアカウント\nhttps://www.instagram.com/tommymizutamaribond/\nーーーーーー\nよく使用している友人のBGM作曲者さん↓\nhttps://twitter.com/gt_k_2014?lang=ja\n素材提供 Music-Note.jp(ミュージックノート)\n他の楽曲提供:Production Music by http://www.epidemicsound.com\n素材提供 PIXTA\n\n#水溜りボンド\n#ドロケイ\n#コムドット"
        },
        "defaultAudioLanguage": "ja"
      },
      "contentDetails": {
        "duration": "PT23M58S",
        "dimension": "2d",
        "definition": "hd",
        "caption": "false",
        "licensedContent": true,
        "contentRating": {},
        "projection": "rectangular"
      },
      "statistics": {
        "viewCount": "337770",
        "likeCount": "17557",
        "dislikeCount": "544",
        "favoriteCount": "0",
        "commentCount": "1650"
      }
    },
 

4. 取得できる情報(part)

確認できた範囲で、どの part にどんな項目が含まれているのか書き出しておきます。

取得できるチャンネル情報

チャンネルの part ではチャンネル名(title)、チャンネル登録者数(subscriberCount)、投稿動画数(videoCount)など、チャンネル単位の情報が取得できます。

part 名称配下の項目
auditDetails投稿主のみアクセス可
brandingSettingschannel, image
contentDetailsrelatedPlaylists
contentOwnerDetails
idチャンネル ID
localizations
snippettitle, description, customUrl, publishedAt, thumbnails, localized, country
statisticsviewCount, subscriberCount, hiddenSubscriberCount, videoCount
statusprivacyStatus, isLinked, longUploadsStatus, madeForKids
topicDetailstopicIds, topicCategories

取得できる動画情報

動画の part では動画タイトル(title)、動画再生回数(viewCount)、いいね数(likeCount)など、 動画単位の情報が取得できます。

part 名称配下の項目
contentDetailsduration, dimension, definition, caption, licensedContent, contentRating, projection
fileDetails投稿主のみアクセス可
id動画 ID
liveStreamingDetailsactualStartTime, scheduledStartTime, concurrentViewers, activeLiveChatId
localizations
playerembedHtml
processingDetails投稿主のみアクセス可
recordingDetails
snippetpublishedAt, channelId, title, description, thumbnails, channelTitle, tags, categoryId, liveBroadcastContent, localized, defaultAudioLanguage
statisticsviewCount, likeCount, dislikeCount, favoriteCount, commentCount
statusuploadStatus, privacyStatus, license, embeddable, publicStatsViewable, madeForKids
suggestions投稿主のみアクセス可
topicDetailstopicCategories

チャンネル情報や動画情報をリクエストする際、一度に指定できる id の数は 50 までの様です。

Matplotlib で描画したグラフを SVG 化して Django で表示する方法

Django アプリケーション内で、データベースから取得したデータをグラフにして表示したいと思ったので方法を調べました。

ざっくりですが、取得した情報を元にグラフの SVG 画像を作成、そしてページに表出する方法を記載します。

  1. テンプレートに img タグを追加
  2. urls.py に URL ディスパッチャを追加
  3. views.py に SVG 描画の処理を追加

1. テンプレートに img タグを追加

テンプレートファイルのグラフを表示したい場所に img タグを追加し、URL 逆引きで URL ディスパッチャを呼び出します。

<img src="{% url 'sample_django_app:yt_trend_svg' %}">

今回は sample_django_app の yt_trend_svg というディスパッチャを呼び出しています。

2. urls.py に URL ディスパッチャを追加

urls.py の urlpatterns リストの中に下記を追加し、yt_trend_svg が呼び出されたら views.py の get_trend_svg 関数を呼び出す様設定しています。

path('chart/', views.get_trend_svg, name="yt_trend_svg"),

3. views.py に SVG 描画の処理を追加

ビューで get_trend_svg 関数を定義し、データの取得、グラフの作成、SVG への変換をして最後に HttpResponse を返します。

処理の流れは下記の通りです。

  1. URL ディスパッチャからget_trend_svg が呼び出される
  2. YtTrendChannel モデルからデータを取り出す
  3. x と y のリストを作成
  4. make_chart 関数に x と y を渡しグラフを作成
  5. convert_to_svg 関数でグラフを SVG に変換
  6. HttpResponse として SVG を返す
import io
from django.http import HttpResponse
import matplotlib
matplotlib.use('Agg') # Matplotlib の backend を指定
import matplotlib.pyplot as plt

# 1. ルーターから get_trend_svg が呼び出される
def get_trend_svg(request):
    
    def make_chart(x, y):
        # setting up plots
        plt.bar(x, y, color='#00d5ff')
        plt.title("My Chart", color='#3407ba')
        plt.xlabel("channel")
        plt.ylabel("views")

    def convert_to_svg():
        # convert the plots to SVG
        buffer = io.BytesIO() # バッファを作成
        plt.savefig(buffer, format='svg', bbox_inches='tight') # バッファに一時保存
        s = buffer.getvalue() # バッファの内容を s に渡す
        buffer.close() # バッファはクローズ
        return s # s を返す
    
    # 2. YtTrendChannel モデルからデータを取り出す
    channels = YtTrendChannel.objects.filter(data_date='20210104').order_by('channel_name')[:10]

    # 3. x と y のリストを作成
    x = [channel.channel_name for channel in channels]
    y = [int(channel.view_count) for channel in channels]

    # 4. make_chart 関数に x と y を渡しグラフを作成
    make_chart(x, y)

    svg = convert_to_svg() # 5. グラフを SVG に変換
    plt.cla()
    
    # 6. HttpResponse として SVG を返す
    return HttpResponse(svg, content_type='image/svg+xml')

convert_to_svg 関数の中でコメントを色々書いていますが、メモリ上に一時ファイルを保存できるため、実ファイルが作られなくて済むんだそうです。

すると下記の様にチャートが表示されます。表示がだいぶ崩れてますがこれは後ほど調整するということで。。。

【mac】PostgreSQL にテーブルを作って csv のデータを挿入した時のメモ

  1. テーブルの作成
  2. csv ファイルをテーブルに copy (insert)
  3. (ついでに)inspectdb でモデル情報を確認

1. テーブルの作成

ターミナルにコマンド「psql データベース名」を入力し対象のデータベースを開いて、別で書いておいた create 文のコピペで処理可能。最後に「;」をつけるのを忘れない様に気をつけてください。

下記の例では「yt_trend_channel」というテーブルを作りました。

sample_db=# create table yt_trend_channel (
channel_id varchar(30),
view_count varchar(20),
join_date varchar(20),
country varchar(20),
channel_name varchar(100),
thumbnail_url varchar(50),
subscriber_count varchar(20),
data_date varchar(8)
);

2. csv ファイルをテーブルに copy (insert)

csv ファイルを テーブルに copy します。

psql を起動する前に対象のファイルのディレクトリへ cd しておくと、単純にファイル名を渡すだけで済むのでわかりやすいです。

下記の例では先ほど create した yt_trend_channel テーブルに、別で用意した yt_trend_channel.csv という csv ファイルのデータを copy (insert) しています。

sample_db=# \copy yt_trend_channel from 'yt_trend_channel.csv' with csv
COPY 4259
sample_db=#

全部で 4259 件のレコードが copy されました。

select クエリで確認します。

sample_db=# select * from yt_trend_channel;
        channel_id        | view_count  | join_date  |    country     |                            channel_name                             |                   thumbnail_url                    | subscriber_count | data_date 
--------------------------+-------------+------------+----------------+---------------------------------------------------------------------+----------------------------------------------------+------------------+-----------
 UC9OvLVXb-okaVtoK9V8Biwg | 103499474   | 2018/05/23 | 日本           | ABEMA バラエティ【公式】                                            | https://yt3.ggpht.com/ytc/AAUvwnjBKC3y2KycvPfvHdn1 |  19.9万人        | 20210104
 UCZZ0UGjWsRdM8_5bsqtxYaQ | 190130764   | 2015/10/02 | 日本           | RIZIN FIGHTING FEDERATION                                           | https://yt3.ggpht.com/ytc/AAUvwnjDj0e-hS0um-ZKG1Tc |  35万人          | 20210104
 UCaminwG9MTO4sLYeC3s6udA | 3201321432  | 2016/03/18 | 日本           | ヒカル(Hikaru)                                                    | https://yt3.ggpht.com/ytc/AAUvwnhBYwfz6DycI4xBURsZ |  428万人         | 20210104
 UCPn_e-7LD7SbzIBxdU_XBnQ | 21113326    | 2020/07/30 | 日本           | あーたろチャンネル                                                  | https://yt3.ggpht.com/ytc/AAUvwngZDvNAYRF_qgPfOgy9 |  18.7万人        | 20210104
 UC4-TMrb7Mm4KnYx1VsUgcJA | 135489838   | 2012/08/04 | 日本           | あいり                                                              | https://yt3.ggpht.com/ytc/AAUvwngy1VncfSpEQkWmZXYK |  26.8万人        | 20210104

ちなみに MySQL の場合は下記の様な感じ

load data local infile  'yt_trend_channel.csv'
into table yt_trend_channel
fields terminated by ',' 
enclosed by '"'
;

3. (ついでに Django)inspectdb でモデル情報を確認

実はそもそも Django で使うテーブルなので「python manage.py inspectdb テーブル名」でモデル情報を確認してみます。

% python manage.py inspectdb yt_trend_channel
# This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
#   * Rearrange models' order
#   * Make sure each model has one field with primary_key=True
#   * Make sure each ForeignKey has `on_delete` set to the desired behavior.
#   * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
# Feel free to rename the models, but don't rename db_table values or field names.
from django.db import models


class YtTrendChannel(models.Model):
    channel_id = models.CharField(max_length=30, blank=True, null=True)
    view_count = models.CharField(max_length=20, blank=True, null=True)
    join_date = models.CharField(max_length=20, blank=True, null=True)
    country = models.CharField(max_length=20, blank=True, null=True)
    channel_name = models.CharField(max_length=100, blank=True, null=True)
    thumbnail_url = models.CharField(max_length=50, blank=True, null=True)
    subscriber_count = models.CharField(max_length=20, blank=True, null=True)
    data_date = models.CharField(max_length=8, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'yt_trend_channel'
% 

class 文を models.py にコピーすると Django でモデルとして使える様になります。その際に 1 つ「primary_key=True」のフィールドを持つ必要がありますので確認してください。

【Django】static ファイルの配置と設定

プロジェクト単位かアプリケーション単位かで若干ファイルの配置場所と設定方法が違いますが、まずは settings.py の INSTALLED_APPS に「'django.contrib.staticfiles'」の記述があることを確認します。

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles', # この記述があることを確認

    'sample_django_app.apps.SampleDjangoAppConfig'
]

プロジェクト単位で使う static の場合

プロジェクトフォルダ(manage.py がある階層)に「static」フォルダを作成し、ファイルを配置。

settings.py の「STATICFILES_DIRS」にフルパスを追加することで、Django が静的ファイルを検索する際の検索対象となります。

collectstatic コマンド実行時のファイル取得元にもなります。

STATICFILES_DIRS = [
    os.path.join(BASE_DIR,'static'),
]

アプリケーション単位で使う static の場合

アプリケーションフォルダ直下に「static/アプリケーション名」のフォルダを作成し、ファイルを配置。

settings.py に「STATIC_URL = '/static/'」の記述があることを確認。

STATIC_URL = '/static/'

参考情報

項目メモ
STATICFILES_DIRScollectstatic が静的ファイルを追加検索する対象のディレクトリ(特定のアプリケーションに属さないものが対象)
STATIC_ROOTcollectstatic 実行時に静的ファイルの集約先となるディレクトリ。下記STATIC_URL の参照先。
STATIC_URL公式ドキュメントには "URL to use when referring to static files located in STATIC_ROOT."(STATIC_ROOT にある静的ファイルを参照する時に使う URL)とあるので、「STATIC_ROOT を表向きの URL としては何と表すか」という事だと理解しています。
参照:Django Documentation - Static Files

また、Django プロジェクト内の静的ファイルを探索するファイルファインダーと呼ばれる仕組みがあり、デフォルトでは下記2つが有効になっています。

  • FileSystemFinder - STATICFILES_DIRS で指定されたディレクトリを探索する
  • AppDirectoriesFinder - アプリケーションレベルの static ディレクトリを探索する

忘備録

アプリケーションレベルの static フォルダを作る際、お作法として直下にアプリケーション名のフォルダを作ってその中に静的ファイルを入れます。

例えば、「app_dir」というアプリケーションに対して「/js/app_script.js」というファイルを作る場合、「app_dir/static/app_name/js/app_script.js」となります。

本番環境で collectstatic コマンドを実行する際、下記の様に static ファイルがコピーされます。

そして、テンプレート上でアプリケーションレベルの静的ファイルを指定する時には「href="{% static 'app_name/css/style.css' %}"」という様にアプリケーション名を合わせて指定することになります。

上記例のテンプレート変数「static」は表向きの URL としては STATIC_URL が紐付き、実際は STATIC_ROOT で指定したディレクトリを参照します。

【mac】Django プロジェクトで PostgreSQL のデータベースを利用する(仮想環境内)

Python 仮想環境内で Django プロジェクト用データベースを PostgreSQL で作成し、Django プロジェクトと紐づける方法を書きます。

今回は例として「sample_db」というデータベース作成し、プロジェクトと紐づけます。

  1. PostgreSQL で新規のデータベースを作成
  2. Django プロジェクトとデータベースの紐付け
  3. 仮想環境で接続用モジュールをインストール
  4. ちなみに
  5. 参考書籍

1. PostgreSQL で新規のデータベースを作成

PostgreSQL を起動し「sample_db」という名前のデータベースを作成します。

% sudo brew services start postgresql
% createdb sample_db

「psql -l」でデータベースのリストを表示すると、「sample_db」が作成されたのが確認できます。

% psql -l
                                         List of databases
   Name    |      Owner       | Encoding | Collate | Ctype |           Access privileges           
-----------+------------------+----------+---------+-------+---------------------------------------
 postgres  | ユーザー名         | UTF8     | C       | C     | 
 sample_db | ユーザー名         | UTF8     | C       | C     | 
 template0 | ユーザー名         | UTF8     | C       | C     | =c/ユーザー名                  +
           |                  |          |         |       | ユーザー名=CTc/ユーザー名
 template1 | ユーザー名         | UTF8     | C       | C     | =c/ユーザー名                  +
           |                  |          |         |       | ユーザー名=CTc/ユーザー名
(4 rows)

ちなみにデータベースを削除したい場合は「dropdb sample_db」と入力します。

2. Django プロジェクトとデータベースの紐付け

Django プロジェクトの settings.py を変更し、先ほど新規作成したデータベースを紐付けます。

プロジェクト作成時に自動作成された settings.py の内容は下記の通り。

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

これを下記の様に変更します。

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'sample_db',
        'USER': os.environ.get('DB_USER'),
        'PASSWORD': os.environ.get('DB_PASSWORD'),
        'HOST': '',
        'PORT': '',
    }
}

またその際にファイル上部に下記を追記し os モジュールをインポートします。

import os

3. 仮想環境で接続用モジュールをインストール

Python で PostgreSQL データベースに接続するために、接続用ドライバのモジュールが必要となります。もっとも多く使われている psycopg2 というモジュールをインストールします。

仮想環境に入った状態で「pip install psycopg2-binary」を実行します。

(sample_venv) % pip install psycopg2-binary
Collecting psycopg2-binary
  Downloading https://files.pythonhosted.org/packages/2c/85/c26507efb110f5a91f503e517f1db55f12ebecb001ff224b2cea234a07ef/psycopg2_binary-2.8.6-cp38-cp38-macosx_10_9_x86_64.macosx_10_9_intel.macosx_10_10_intel.macosx_10_10_x86_64.whl (1.5MB)
     |████████████████████████████████| 1.5MB 7.1MB/s 
Installing collected packages: psycopg2-binary
Successfully installed psycopg2-binary-2.8.6
WARNING: You are using pip version 19.2.3, however version 21.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
(sample_venv) % 

4. ちなみに

PyCharm の runserver を実行した時に下記のエラーが出て一瞬焦りましたが、PostgreSQL を起動したら治りました。

django.db.utils.OperationalError: could not connect to server: No such file or directory

ちなみのちなみに、settings.py の「DATABASES」の部分をコメントアウトなどするとデータベースを起動していなくても問題なく runserver を実行できます。

5. 参考書籍

僕は始め下記の書籍に沿って Django の全体像を勉強しました。書籍は PostgreSQL を使用した開発になっているので参考にしてみてください。

動かして学ぶ! Python Django開発入門 (NEXT ONE)

Mac に PostgreSQL をインストールする

Homebrew を使って PostgreSQL の最新バーションをインストールします。

実行環境:maxOS Big Sur バージョン 11.2.2

  1. PostgreSQL をインストールする
  2. PostgreSQL を起動・終了する

PostgreSQL をインストールする

下記のコマンドを実行します。

% brew install postgresql

ログが表示されます。(下記のログには Homebrew 自体の自動アップデートなど余分なものも含まれてます。)

% brew install postgresql            
Updating Homebrew...
==> Auto-updated Homebrew!
Updated 1 tap (homebrew/core).
==> New Formulae
aerc                       hblock                     php@7.4
aida-header                heppdt2                    pickle
aliddns                    hexo                       pkger
ansible@2.9                htmltest                   projectm
arturo                     iconsur                    ptpython
as-tree                    indicators                 pyqt-3d
atkmm@2.28                 inframap                   pyqt-builder
attr                       isl@0.18                   pyqt-networkauth
aws-console                isort                      pyqt@5
aws-rotate-key             jpeg-xl                    pyside@2
bandit                     jql                        python-tabulate
bas55                      json5                      qt-libiodbc
bit-git                    k3sup                      qt-mariadb
blaze                      kcgi                       qt-mysql
bpython                    keptn                      qt-percona-server
bpytop                     khiva                      qt-postgresql
cairomm@1.14               klee                       qt-unixodbc
cargo-audit                ko                         rain
cargo-edit                 kotlin-language-server     rdkit
cargo-watch                kube-linter                regipy
cfn-flip                   kubecm                     richmd
cfn-format                 kubergrunt                 rm-improved
chars                      kubevela                   rtl_433
checkov                    lab                        rttr
cherrytree                 latino                     ruby@2.7
clash                      libbsd                     saml2aws
cloudflare-wrangler        libcap                     showkey
coin3d                     libcap-ng                  snowpack
condure                    libfuse                    spack
counterfeiter              libmd                      sqlancer
cpplint                    libnsl                     sqlc
crane                      libpinyin                  strace
crcany                     libpipeline                t-rec
crispy-doom                libprelude                 taskwarrior-tui
curlie                     librttopo                  tctl
cyrus-sasl                 libslirp                   tendermint
dasel                      libtirpc                   terracognita
datalad                    libva                      terraform@0.13
delve                      libvdpau                   tgenv
device-mapper              libvnc                     thrax
dnsx                       libxml++@4                 tm
docui                      libxml++@5                 tomcat@9
dog                        libxp                      trec_eval
dotenv-linter              linux-headers              tree-sitter
dprint                     logswan                    truffle
driftctl                   lp_solve                   utf8cpp
dstask                     lua@5.3                    v2ray
duf                        luajit-openresty           vc
easy-rsa                   luv                        vint
efm-langserver             magic_enum                 vitess
enzyme                     markdownlint-cli           vsh
evernote2md                massdns                    vulture
f3d                        md4c                       waffle
fizz                       mermaid-cli                wangle
flow-cli                   mesa-glu                   wayland
flux                       mockery                    wayland-protocols
fnm                        mpdecimal                  wllvm
forge                      msc-generator              xbitmaps
gallery-dl                 muffet                     xcb-util
gcalcli                    name-that-hash             xcb-util-cursor
gdu                        ncspot                     xcb-util-image
geph4                      nicotine-plus              xcb-util-keysyms
ghc@9                      node@14                    xcb-util-renderutil
gitlint                    nuclei                     xcb-util-wm
giza                       oakc                       xcbeautify
glab                       ocaml-zarith               xcinfo
glibc                      open-adventure             xcprojectlint
go@1.15                    openalpr                   xinput
gofumpt                    openjdk@8                  xkeyboardconfig
gojq                       openmama                   xorgrgb
googletest                 openmodelica               xray
gopass-jsonapi             or-tools                   xterm
gopls                      oras                       yh
goredo                     osmcoastline               ykdl
gosec                      overdrive                  youtube-dlc
gost                       ox                         youtubedr
gping                      parliament                 yq@3
grokj2k                    pcalc                      yubikey-agent
grokmirror                 pdftilecut                 zsh-async
gtkmm4                     pdm
h2spec                     phive
==> Updated Formulae
Updated 5020 formulae.
==> Renamed Formulae
glibmm@2.64 -> glibmm@2.66               pangomm@2.42 -> pangomm@2.46
gtk+4 -> gtk4                            prest -> prestd
ht-rust -> xh                            qt5 -> qt@5
now-cli -> vercel-cli
==> Deleted Formulae
avian                      gobby                      scw@1
boost@1.55                 godep                      stlviewer
boost@1.59                 llvm@6                     unp64
confluent-platform         meson-internal             unrar
curl-openssl               mysql-connector-c++@1.1    woboq_codebrowser
dtrx                       ori                        xspin
fmsx                       pgplot
geant4                     rmtrash

==> Downloading https://homebrew.bintray.com/bottles/icu4c-68.2.big_sur.bottle.t
==> Downloading from https://d29vzk4ow07wi7.cloudfront.net/ba2fd8c7d37025c93db6b
######################################################################## 100.0%
==> Downloading https://homebrew.bintray.com/bottles/openssl%401.1-1.1.1j.big_su
==> Downloading from https://d29vzk4ow07wi7.cloudfront.net/5725361adcd088a5b4fb2
######################################################################## 100.0%
==> Downloading https://homebrew.bintray.com/bottles/krb5-1.19.1.big_sur.bottle.
==> Downloading from https://d29vzk4ow07wi7.cloudfront.net/d544c1111503eb27b253e
######################################################################## 100.0%
==> Downloading https://homebrew.bintray.com/bottles/readline-8.1.big_sur.bottle
==> Downloading from https://d29vzk4ow07wi7.cloudfront.net/2cc3a9582e3c7e21eb3c2
######################################################################## 100.0%
==> Downloading https://homebrew.bintray.com/bottles/postgresql-13.2_1.big_sur.b
==> Downloading from https://d29vzk4ow07wi7.cloudfront.net/67a547842ae49911d301d
######################################################################## 100.0%
==> Installing dependencies for postgresql: icu4c, openssl@1.1, krb5 and readline
==> Installing postgresql dependency: icu4c
==> Pouring icu4c-68.2.big_sur.bottle.tar.gz
==> Caveats
icu4c is keg-only, which means it was not symlinked into /usr/local,
because macOS provides libicucore.dylib (but nothing else).

If you need to have icu4c first in your PATH, run:
  echo 'export PATH="/usr/local/opt/icu4c/bin:$PATH"' >> ~/.zshrc
  echo 'export PATH="/usr/local/opt/icu4c/sbin:$PATH"' >> ~/.zshrc

For compilers to find icu4c you may need to set:
  export LDFLAGS="-L/usr/local/opt/icu4c/lib"
  export CPPFLAGS="-I/usr/local/opt/icu4c/include"

==> Summary
🍺  /usr/local/Cellar/icu4c/68.2: 259 files, 72.5MB
==> Installing postgresql dependency: openssl@1.1
==> Pouring openssl@1.1-1.1.1j.big_sur.bottle.tar.gz
==> Caveats
A CA file has been bootstrapped using certificates from the system
keychain. To add additional certificates, place .pem files in
  /usr/local/etc/openssl@1.1/certs

and run
  /usr/local/opt/openssl@1.1/bin/c_rehash

openssl@1.1 is keg-only, which means it was not symlinked into /usr/local,
because macOS provides LibreSSL.

If you need to have openssl@1.1 first in your PATH, run:
  echo 'export PATH="/usr/local/opt/openssl@1.1/bin:$PATH"' >> ~/.zshrc

For compilers to find openssl@1.1 you may need to set:
  export LDFLAGS="-L/usr/local/opt/openssl@1.1/lib"
  export CPPFLAGS="-I/usr/local/opt/openssl@1.1/include"

==> Summary
🍺  /usr/local/Cellar/openssl@1.1/1.1.1j: 8,071 files, 18.5MB
==> Installing postgresql dependency: krb5
==> Pouring krb5-1.19.1.big_sur.bottle.tar.gz
==> Caveats
krb5 is keg-only, which means it was not symlinked into /usr/local,
because macOS already provides this software and installing another version in
parallel can cause all kinds of trouble.

If you need to have krb5 first in your PATH, run:
  echo 'export PATH="/usr/local/opt/krb5/bin:$PATH"' >> ~/.zshrc
  echo 'export PATH="/usr/local/opt/krb5/sbin:$PATH"' >> ~/.zshrc

For compilers to find krb5 you may need to set:
  export LDFLAGS="-L/usr/local/opt/krb5/lib"
  export CPPFLAGS="-I/usr/local/opt/krb5/include"

==> Summary
🍺  /usr/local/Cellar/krb5/1.19.1: 162 files, 5.2MB
==> Installing postgresql dependency: readline
==> Pouring readline-8.1.big_sur.bottle.tar.gz
==> Caveats
readline is keg-only, which means it was not symlinked into /usr/local,
because macOS provides BSD libedit.

For compilers to find readline you may need to set:
  export LDFLAGS="-L/usr/local/opt/readline/lib"
  export CPPFLAGS="-I/usr/local/opt/readline/include"

==> Summary
🍺  /usr/local/Cellar/readline/8.1: 48 files, 1.6MB
==> Installing postgresql
==> Pouring postgresql-13.2_1.big_sur.bottle.tar.gz
==> /usr/local/Cellar/postgresql/13.2_1/bin/initdb --locale=C -E UTF-8 /usr/loca
==> Caveats
To migrate existing data from a previous major version of PostgreSQL run:
  brew postgresql-upgrade-database

This formula has created a default database cluster with:
  initdb --locale=C -E UTF-8 /usr/local/var/postgres
For more details, read:
  https://www.postgresql.org/docs/13/app-initdb.html

To have launchd start postgresql now and restart at login:
  brew services start postgresql
Or, if you don't want/need a background service you can just run:
  pg_ctl -D /usr/local/var/postgres start
==> Summary
🍺  /usr/local/Cellar/postgresql/13.2_1: 3,218 files, 42.6MB
==> `brew cleanup` has not been run in 30 days, running now...
Removing: /Users/ユーザー名/Library/Caches/Homebrew/mysql--8.0.21_1.catalina.bottle.tar.gz... (80.4MB)
Removing: /usr/local/Cellar/openssl@1.1/1.1.1h... (8,067 files, 18.5MB)
Removing: /Users/ユーザー名/Library/Caches/Homebrew/openssl@1.1--1.1.1h.catalina.bottle.tar.gz... (5.4MB)
Removing: /Users/ユーザー名/Library/Caches/Homebrew/protobuf--3.13.0.catalina.bottle.tar.gz... (4.8MB)
Removing: /Users/ユーザー名/Library/Logs/Homebrew/mysql... (1.1KB)
Removing: /Users/ユーザー名/Library/Logs/Homebrew/protobuf... (64B)
Pruned 1 symbolic links and 2 directories from /usr/local
==> Upgrading 2 dependents:
mysql 8.0.21_1 -> 8.0.23_1, wget 1.20.3_2 -> 1.21.1
==> Upgrading mysql 8.0.21_1 -> 8.0.23_1 
==> Downloading https://homebrew.bintray.com/bottles/protobuf-3.15.5.big_sur.bot
==> Downloading from https://d29vzk4ow07wi7.cloudfront.net/872baaeb92aaaaa8d2634
######################################################################## 100.0%
==> Downloading https://homebrew.bintray.com/bottles/mysql-8.0.23_1.big_sur.bott
==> Downloading from https://d29vzk4ow07wi7.cloudfront.net/9e9e4b5bfcad47adfbf7f
######################################################################## 100.0%
==> Installing dependencies for mysql: protobuf
==> Installing mysql dependency: protobuf
==> Pouring protobuf-3.15.5.big_sur.bottle.tar.gz
==> Caveats
Emacs Lisp files have been installed to:
  /usr/local/share/emacs/site-lisp/protobuf
==> Summary
🍺  /usr/local/Cellar/protobuf/3.15.5: 211 files, 17.7MB
==> Installing mysql
==> Pouring mysql-8.0.23_1.big_sur.bottle.tar.gz
==> Caveats
We've installed your MySQL database without a root password. To secure it run:
    mysql_secure_installation

MySQL is configured to only allow connections from localhost by default

To connect run:
    mysql -uroot

To have launchd start mysql now and restart at login:
  brew services start mysql
Or, if you don't want/need a background service you can just run:
  mysql.server start
==> Summary
🍺  /usr/local/Cellar/mysql/8.0.23_1: 298 files, 297.7MB
Removing: /usr/local/Cellar/mysql/8.0.21_1... (290 files, 291.2MB)
==> Upgrading wget 1.20.3_2 -> 1.21.1 
==> Downloading https://homebrew.bintray.com/bottles/gettext-0.21.big_sur.bottle
==> Downloading from https://d29vzk4ow07wi7.cloudfront.net/a025e143fe3f5f7e24a93
######################################################################## 100.0%
==> Downloading https://homebrew.bintray.com/bottles/wget-1.21.1.big_sur.bottle.
==> Downloading from https://d29vzk4ow07wi7.cloudfront.net/e6ea2a50b8196206f7072
######################################################################## 100.0%
==> Installing dependencies for wget: gettext
==> Installing wget dependency: gettext
==> Pouring gettext-0.21.big_sur.bottle.tar.gz
🍺  /usr/local/Cellar/gettext/0.21: 1,953 files, 19.8MB
==> Installing wget
==> Pouring wget-1.21.1.big_sur.bottle.tar.gz
🍺  /usr/local/Cellar/wget/1.21.1: 88 files, 4MB
Removing: /usr/local/Cellar/wget/1.20.3_2... (50 files, 4.0MB)
==> Checking for dependents of upgraded formulae...
==> No broken dependents found!
==> Caveats
==> icu4c
icu4c is keg-only, which means it was not symlinked into /usr/local,
because macOS provides libicucore.dylib (but nothing else).

If you need to have icu4c first in your PATH, run:
  echo 'export PATH="/usr/local/opt/icu4c/bin:$PATH"' >> ~/.zshrc
  echo 'export PATH="/usr/local/opt/icu4c/sbin:$PATH"' >> ~/.zshrc

For compilers to find icu4c you may need to set:
  export LDFLAGS="-L/usr/local/opt/icu4c/lib"
  export CPPFLAGS="-I/usr/local/opt/icu4c/include"

==> openssl@1.1
A CA file has been bootstrapped using certificates from the system
keychain. To add additional certificates, place .pem files in
  /usr/local/etc/openssl@1.1/certs

and run
  /usr/local/opt/openssl@1.1/bin/c_rehash

openssl@1.1 is keg-only, which means it was not symlinked into /usr/local,
because macOS provides LibreSSL.

If you need to have openssl@1.1 first in your PATH, run:
  echo 'export PATH="/usr/local/opt/openssl@1.1/bin:$PATH"' >> ~/.zshrc

For compilers to find openssl@1.1 you may need to set:
  export LDFLAGS="-L/usr/local/opt/openssl@1.1/lib"
  export CPPFLAGS="-I/usr/local/opt/openssl@1.1/include"

==> krb5
krb5 is keg-only, which means it was not symlinked into /usr/local,
because macOS already provides this software and installing another version in
parallel can cause all kinds of trouble.

If you need to have krb5 first in your PATH, run:
  echo 'export PATH="/usr/local/opt/krb5/bin:$PATH"' >> ~/.zshrc
  echo 'export PATH="/usr/local/opt/krb5/sbin:$PATH"' >> ~/.zshrc

For compilers to find krb5 you may need to set:
  export LDFLAGS="-L/usr/local/opt/krb5/lib"
  export CPPFLAGS="-I/usr/local/opt/krb5/include"

==> readline
readline is keg-only, which means it was not symlinked into /usr/local,
because macOS provides BSD libedit.

For compilers to find readline you may need to set:
  export LDFLAGS="-L/usr/local/opt/readline/lib"
  export CPPFLAGS="-I/usr/local/opt/readline/include"

==> postgresql
To migrate existing data from a previous major version of PostgreSQL run:
  brew postgresql-upgrade-database

This formula has created a default database cluster with:
  initdb --locale=C -E UTF-8 /usr/local/var/postgres
For more details, read:
  https://www.postgresql.org/docs/13/app-initdb.html

To have launchd start postgresql now and restart at login:
  brew services start postgresql
Or, if you don't want/need a background service you can just run:
  pg_ctl -D /usr/local/var/postgres start
==> protobuf
Emacs Lisp files have been installed to:
  /usr/local/share/emacs/site-lisp/protobuf
==> mysql
We've installed your MySQL database without a root password. To secure it run:
    mysql_secure_installation

MySQL is configured to only allow connections from localhost by default

To connect run:
    mysql -uroot

To have launchd start mysql now and restart at login:
  brew services start mysql
Or, if you don't want/need a background service you can just run:
  mysql.server start
% 

コマンド「psql --version」を実行し、PostgreSQL のバージョンが正常に表示されれば問題ありません。

% psql --version
psql (PostgreSQL) 13.2

PostgreSQL を起動・終了する

「brew services start postgresql」で起動します。初回起動時のみ下記の様なログが表示されますが、2回目以降は表示されません。

% brew services start postgresql
==> Tapping homebrew/services
Cloning into '/usr/local/Homebrew/Library/Taps/homebrew/homebrew-services'...
remote: Enumerating objects: 20, done.
remote: Counting objects: 100% (20/20), done.
remote: Compressing objects: 100% (20/20), done.
remote: Total 1141 (delta 8), reused 0 (delta 0), pack-reused 1121
Receiving objects: 100% (1141/1141), 331.40 KiB | 5.18 MiB/s, done.
Resolving deltas: 100% (485/485), done.
Tapped 1 command (41 files, 420.9KB).
==> Successfully started `postgresql` (label: homebrew.mxcl.postgresql)
%

コマンド「psql -l」を実行するとデータベースの一覧が参照できます。

% psql -l
                                         List of databases
   Name    |      Owner       | Encoding | Collate | Ctype |           Access privileges           
-----------+------------------+----------+---------+-------+---------------------------------------
 postgres  | ユーザー名         | UTF8     | C       | C     | 
 template0 | ユーザー名         | UTF8     | C       | C     | =c/ユーザー名                  +
           |                  |          |         |       | ユーザー名=CTc/ユーザー名
 template1 | ユーザー名         | UTF8     | C       | C     | =c/ユーザー名                  +
           |                  |          |         |       | ユーザー名=CTc/ユーザー名
(3 rows)
%

「brew services stop postgresql」で終了

% brew services stop postgresql
Stopping `postgresql`... (might take a while)
==> Successfully stopped `postgresql` (label: homebrew.mxcl.postgresql)
% 

【mac】Python 仮想環境に Django プロジェクトを作成する方法

  1. Python 仮想環境の作成
  2. Django のインストール
  3. Django プロジェクトの作成
  4. Django アプリケーションの作成
  5. アプリケーションをプロジェクトに登録
  6. 動作確認
  7. 初期マイグレーション
  8. 管理ユーザーの作成

1. Python 仮想環境の作成

仮想環境を作成したいディレクトリへ行き、下記のコマンドを実行します。例として「sample_venv」という仮想環境を作ります。

 python3 -m venv sample_venv

すると下記の様に Python の実行に必要なファイルやフォルダが一式作成されます。

これで仮想環境の作成は完了です。実際に仮想環境「sample_venv」を起動するには下記を実行します。

% cd sample_venv
% source bin/activate

下記の様にカッコの中に仮想環境の名前が表示されると思います。

(sample_venv) %

仮想環境から出たい場合は「deactivate」を実行します。

(sample_venv) % deactivate
%

2. Django のインストール

仮想環境で Django をインストールするには、仮想環境を activate した状態で下記を実行します。

(sample_venv) % pip install django

下記のようなログが表示されて最後の方に「Successfully installed」と出ていれば成功です。

(sample_venv) % pip install django
Collecting django
  Downloading https://files.pythonhosted.org/packages/b8/6f/9a4415cc4fe9228e26ea53cf2005961799b2abb8da0411e519fdb74754fa/Django-3.1.7-py3-none-any.whl (7.8MB)
     |████████████████████████████████| 7.8MB 337kB/s 
Collecting asgiref<4,>=3.2.10 (from django)
  Downloading https://files.pythonhosted.org/packages/89/49/5531992efc62f9c6d08a7199dc31176c8c60f7b2548c6ef245f96f29d0d9/asgiref-3.3.1-py3-none-any.whl
Collecting sqlparse>=0.2.2 (from django)
  Downloading https://files.pythonhosted.org/packages/14/05/6e8eb62ca685b10e34051a80d7ea94b7137369d8c0be5c3b9d9b6e3f5dae/sqlparse-0.4.1-py3-none-any.whl (42kB)
     |████████████████████████████████| 51kB 9.6MB/s 
Collecting pytz (from django)
  Downloading https://files.pythonhosted.org/packages/70/94/784178ca5dd892a98f113cdd923372024dc04b8d40abe77ca76b5fb90ca6/pytz-2021.1-py2.py3-none-any.whl (510kB)
     |████████████████████████████████| 512kB 8.1MB/s 
Installing collected packages: asgiref, sqlparse, pytz, django
Successfully installed asgiref-3.3.1 django-3.1.7 pytz-2021.1 sqlparse-0.4.1
WARNING: You are using pip version 19.2.3, however version 21.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
(sample_virtual_environment) %

これで Python の仮想環境に Django がインストールされたので、この後 Django のプロジェクト、アプリケーションを作っていきます。

3. Django プロジェクトの作成

仮想環境に入った状態で下記を実行します。今回は例として仮想環境内に「Django_Project」フォルダを作り、その中に「sample_django_project」という名前の Django プロジェクトを作成します。

(sample_venv) % mkdir Django_Project
(sample_venv) % cd Django_Project
(sample_venv) Django_Project % django-admin startproject sample_django_project

すると下記の様に「Django_Project」フォルダの配下に「sample_django_project」フォルダとファイルが一式作成されます。

4. Django アプリケーションの作成

上の画像「manage.py」がある階層へ移動します。

(sample_venv) % cd sample_django_project

そして下記を実行して「sample_django_app」という名前で Django アプリケーションを作成します。

(sample_venv) sample_django_project % python manage.py startapp sample_django_app

すると、「sample_django_project」というプロジェクトの配下に「sample_django_app」が作成されました。

5. アプリケーションをプロジェクトに登録

アプリケーションフォルダの apps.py を開くと下記の通り「SampleDjangoAppConfig」というクラスがあるので、このクラス名をプロジェクトの settings.py に登録します。

# apps.py
from django.apps import AppConfig


class SampleDjangoAppConfig(AppConfig):
    name = 'sample_django_app'

settings.py の INSTALLED_APPS のリストに下記の通り「アプリケーション名.apps.クラス名」の形で追記します。

# settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'sample_django_app.apps.SampleDjangoAppConfig'
]

これで Django プロジェクトと Django アプリケーションの作成は完了です。

6. 動作確認

ターミナルでコマンド「python manage.py runserver」を実行し、動作確認をします。

% python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).

You have 18 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.
April 23, 2021 - 21:27:24
Django version 3.2, using settings 'sample_django_project.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

特に問題がなければ上記の様なログが表示されるはずです。

そしてブラウザの URL バーに「http://127.0.0.1:8000/」と入力して下記の画面が表示されたら OK です。

停止したい場合は CONTROL-C を押下します。

7. 初期マイグレーション

Django の設定内容やモデルの構造をデータベースへ反映することをマイグレーションと呼びます。

Django ではデフォルトのデータベースとして SQLite が設定されているので他のデータベースを使用する場合は先にデータベースの変更をしてください。例として PostgreSQL を使用する場合の例を下記に貼っておきます。

Django プロジェクトで PostgreSQL のデータベースを利用する(仮想環境内)

Django プロジェクト・アプリケーションの作成時点ではマイグレーションされていない設定内容がいくつかありますのでコマンド「python manage.py migrate」を実行してマイグレーションをおこないます。

% python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying auth.0012_alter_user_first_name_max_length... OK
  Applying sessions.0001_initial... OK

8. 管理ユーザーの作成

仮想環境内、「manage.py」のある階層でコマンド「python manage.py createsuperuser」を実行します。

% python manage.py createsuperuser

するとユーザー名、メールアドレスをパスワードを設定する様促されるので設定を行います。

Username : adminuser #任意のユーザー名
Email address: xxxxxxxx@gmail.com
Password: 
Password (again): 
Superuser created successfully.
% python manage.py runserver

ブラウザで「http://127.0.0.1:8000/admin/」にアクセスすると、管理ユーザーのログイン画面が表示されます。

ログインすると下記の通り管理ユーザー用画面が表示されます。