Django練習
はじめに
Djangoの勉強をはじめました。最初はソースコードの写経をしていましたが原理を知らないまま写経をしても意味がないと思いとりあえず今日やった下記の操作を説明できるようになる事をまずは目標とします。
後日下記操作の意味を追記するようにしたいと思います。
プロジェクトの作成
$ django-admin startproject project2
アプリケーションの作成
$ python3.7 manage.py startup employee
Djangoの管理画面を利用する為マイグレートの実行
$ python3.7 manage.py migrate
スーパーユーザの作成
$ python3.7 manage.py createsuperuser
setting.pyの編集
project2ディレクトリ配下の「settings.py」を編集する。
編集箇所は2箇所
INSTALLED_APPS
INSTALLED_APPS = [ 'employee.apps.EmployeeConfig', #この行を追加 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ]
urls.pyの編集
path関数の追加
from django.urls import path
pathnの追加
urlpatterns = [ path('admin/', admin.site.urls), path('', include('employee.urls')) ]
employeeディレクトリ配下に「urls.py」を作成
from django.urls import path,include from . import views app_name = 'employee' urlpatterns = [ path('',views.IndexViews.as_view(), name='index') ]
views.pyの編集
from django.views import generic class IndexView(generic.TemplateView): template_name = 'employee/employee_list.html'
base.htmlの作成
プロジェクトディレクトリ「employee」配下に「templates」というディクトりを作成し、その配下に「employee」を作成します。
その後、下記内容で「base.html」を作成します。
<!doctype html> <html lang="ja"> <head> <title>社員管理システム</title> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous"> </head> <body> {% block content %} {% endblock %} </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script> </body> </html>
employee_list.htmlの作成
base.htmlと同階層に「employee_list.html」を下記内容で作成します。
{% extends 'employee/base.html' %} {% block content %} トップページ {% endblock %}
Djangoの起動
$ python3.7 manage.py runserver 0.0.0.0:8000
エラーが・・
「Invalid HTTP_HOST header: '132.***.***.60:8000'. You may need to add '132.***.***.60' to ALLOWED_HOSTS.」
解決策
「settings.py」の「ALLOWED_HOSTS」に設定追加する。
ALLOWED_HOSTS = ['132.***.***.60']
問題なくアクセスできました。
[opc@django project2]$ curl http://132.145.122.60:8000/ <!doctype html> <html lang="ja"> <head> <title>社員管理システム</title> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous"> </head> <body> トップページ </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script> </body> </html>[opc@django project2]$
django.db.utils.OperationalError: attempt to write a readonly databaseエラー対応
Djangoの管理ユーザを作成しようとすると下記のエラーが発生。
「django.db.utils.OperationalError: attempt to write a readonly database」
「readonly database」から書込み権限が無いと推測できる。
とりあえずググってみた。ありましたね。今回も先人様のお知恵をお借りいたします。
ありがとうございます。
ayahito2828.hatenablog.com
[opc@django project]python3.7 manage.py createsuperuser ユーザー名 (leave blank to use 'opc'): メールアドレス: opc@example.com Password: Password (again): Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/usr/local/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 413, in execute 〜エラー内容省略〜 django.db.utils.OperationalError: attempt to write a readonly database [opc@django project]$ [opc@django project]$ chmod 766 db.sqlite3 chmod: changing permissions of ‘db.sqlite3’: Operation not permitted [opc@django project]$ [opc@django project]$ sudo chmod 766 db.sqlite3 [opc@django project]$ python3.7 manage.py createsuperuser ユーザー名 (leave blank to use 'opc'): メールアドレス: opc@example.com Password: Password (again): Superuser created successfully. [opc@django project]$
無事スーパーユーザ作成できました。
Edge Router X でDHCP Serverの設定してみた
数日前に久しぶりにEdge Routerを使おうとした時にコンフィグのバックアップを取ってなくてどのインタフェースにどのアドレスを割り振ったか忘れてしまい結局初期化する羽目になりました。。。
コンフィグも結構色々設定入れていたので初期化するのは本当に忍なかった。。。
そんな失敗を次繰り返さないように特定のポートにDHCPサーバの設定を入れ、アドレスを忘れても繋がるようにしたいと思います。
DHCPサーバ設定例
set service dhcp-server shared-network-name LAN1 subnet 192.168.0.0/24 default-router 192.168.0.1 set service dhcp-server shared-network-name LAN1 subnet 192.168.0.0/24 dns-server 192.168.0.1 set service dhcp-server shared-network-name LAN1 subnet 192.168.0.0/24 start 192.168.0.100 stop 192.168.0.200
実際に設定追加してみる
今回はeth4をDHCP設定するポートとします。
set interfaces ethernet eth4 address 172.16.0.254/24 set service dhcp-server shared-network-name LAN1 subnet 172.16.0.0/24 default-router 172.16.0.254 set service dhcp-server shared-network-name LAN1 subnet 172.16.0.0/24 dns-server 172.16.0.254 set service dhcp-server shared-network-name LAN1 subnet 172.16.0.0/24 start 172.16.0.1 stop 172.16.0.200
以上で設定完了です。
DHCPサーバの動作確認
どうでしょうか。問題なく172.16.0.1のアドレスが割り振られていますね。
Python3でgoogleスプレッドシートを使ってみる。
Python3 でgoogleスプレッドシートを使ってみたので覚書として残します。
Google スプレッドシートの準備
Googleスプレッドシートで下記を有効にしますが、手順はコチラをご参照ください、
・Google Drive APIを有効
・Google Sheets API
Pythonプログラム
import gspread from oauth2client.service_account import ServiceAccountCredentials scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive'] credentials = ServiceAccountCredentials.from_json_keyfile_name('<ダウンロードしたJSONファイル名>.json', scope) gc = gspread.authorize(credentials) wks = gc.open('test').sheet1 wks.update_acell('A3', 'Hello World!')
vs Codeで開発するDjangoのエラー「Class has no 'Objects' member」解消方法
Visual Studio Code(vs Code)でDjangoを開発しているとよく出るエラーの一つがこちら「Class has no 'Objects' member」
今回はこちらのエラー解消を紹介します。
pylintの追加モジュールをインストール
pip3.7 install pylint-django
Edge Router X WireGuard構築してみた
最近購入したEdge Router XでWireGuardを動かせるそうなのでやってみました。
以前にUbuntu 20.04でやってみましたが、今回はガチモンのルータでやってみます。
毎回恒例の参考記事の紹介と謝辞です。ありがとうございます。
www.blog.slow-fire.net
neontom.com
ERX用のWireGuardインストーラの入手
下記URLのインストーラをローカルPCにダウンロードします。
※ERX用のインストーラです。
https://github.com/WireGuard/wireguard-vyatta-ubnt/releases/download/1.0.20200506-2/e50-v2-v1.0.20200506-v1.0.20200510.deb
インストーラをERXへアップロード
SCPを使ってERXへアップロードします。
$ scp e50-v2-v1.0.20200506-v1.0.20200510.deb ubnt@192.168.1.1:/home/ubnt Welcome to EdgeOS By logging in, accessing, or using the Ubiquiti product, you acknowledge that you have read and understood the Ubiquiti License Agreement (available in the Web UI at, by default, http://192.168.1.1) and agree to be bound by its terms. ubnt@192.168.1.1's password: e50-v2-v1.0.20200506-v1.0.20200510.deb 100% 167KB 7.1MB/s 00:00
WireGuardのインストール
# dpkg -i e50-v2-v1.0.20200506-v1.0.20200510.deb
下記の通りに表示されていればOK
Unpacking wireguard (1.0.20200506-2) ... Setting up wireguard (1.0.20200506-2) ...
ERXでの諸々の設定
wg genkey | tee /config/auth/wg.key | wg pubkey > wg.public set interfaces wireguard wg0 address 10.255.255.1/24 set interfaces wireguard wg0 listen-port 51820 set interfaces wireguard wg0 route-allowed-ips true set interfaces wireguard wg0 private-key /config/auth/wg.key set firewall name WAN_LOCAL rule 20 action accept set firewall name WAN_LOCAL rule 20 description 'WireGuard' set firewall name WAN_LOCAL rule 20 destination port 51820 set firewall name WAN_LOCAL rule 20 protocol udp commit; save; exit
インターフェースの公開鍵の確認
root@ubnt:~$ sudo wg interface: wg0 public key: ***************************** private key: (hidden) listening port: 51820
ここまででERXでの設定8割完了です。
クライアント端末設定
今回クライアント端末はWindowsで検証しました。
まずはWireGuardのWindowsクライアントを入手します。
こちらからDLしてください
クライアントの起動と設定
クライアントを起動後、画面左下の「トンネルの追加」>「空のトンネルの追加」をクリックする。
すると公開鍵と秘密鍵が勝手に作ってくれている。
続いて下記のように設定を追加していく。
[Interface] PrivateKey = <クライアント側の秘密鍵> Address = 10.255.255.2/24 [Peer] PublicKey = <ERX側の公開鍵> AllowedIPs = 0.0.0.0/0 Endpoint = 192.168.1.1:51820
ERXでクライアントの設定
set interfaces wireguard wg0 peer <クライアントの公開鍵> allowed-ips 10.255.255.2/32
以上で設定完了です。
クライアントアプリから有効化し、10.255.255.1へのPingが飛ぶ事を確認しましょう。
Edge Router X ファームウェアバージョンアップ手順
先日届いた勉強用のルータ「Edge Router X」のファームウェアがv1だったのでv2でアップデートしたいと思います。
ファームウェアの入手の前に
ファームウェアのURL
https://dl.ubnt.com/firmwares/edgemax/v2.0.x/ER-e50.v2.0.0.5155111.tar
ERXがインターネットに繋がっていればERXから直接ダウンロードして頂いて良いんですが、あいにくと私のERX環境ではまだインターネット環境へのアクセスができない状態でした。
なので一度ローカルPCに落としてからERXのGUI経由でファームウェアをERXへアップロードします。
ファームウェアの入手
$ wget https://dl.ubnt.com/firmwares/edgemax/v2.0.x/ER-e50.v2.0.0.5155111.tar --2020-10-10 23:22:58-- https://dl.ubnt.com/firmwares/edgemax/v2.0.x/ER-e50.v2.0.0.5155111.tar dl.ubnt.com (dl.ubnt.com) をDNSに問いあわせています... 99.86.199.94 dl.ubnt.com (dl.ubnt.com)|99.86.199.94|:443 に接続しています... 接続しました。 HTTP による接続要求を送信しました、応答を待っています... 200 OK 長さ: 83619840 (80M) [application/x-tar] `ER-e50.v2.0.0.5155111.tar' に保存中 ER-e50.v2.0.0.51551 100%[===================>] 79.75M 14.8MB/s 時間 6.8s 2020-10-10 23:23:05 (11.7 MB/s) - `ER-e50.v2.0.0.5155111.tar' へ保存完了 [83619840/83619840]
ERXのGUIにログイン
ブラウザからhttp://192.168.1.1でアクセスできます。確かデフォルトはeth1にそのIPアドレスが設定されていたはず。。。
で、アクセスしてみるとユーザ とパスワードを求められるので ubnt/ubntでログインします。
ログインできると下記のようなダッシュボード画面が表示されます。
ファームウェアのアップロードと実行
ERXのダッシュボード画面最下部に「system」ボタンがあるのでクリックする。
するとシステム画面が現れるのでスクロールし、下記画面を探す。
「Upload a File」をクリックし、wgetでダウンロードしたファイルを選択する。
%表記でアップロードが行われアップロード後自動で適用される。
ファームウェアの確認
無事にv2で上がっていることを確認する。
ubnt@ubnt:~$ show version Version: v2.0.0 Build ID: 5155111 Build on: 01/03/19 16:39 Copyright: 2012-2018 Ubiquiti Networks, Inc. HW model: EdgeRouter X 5-Port HW S/N: 74ACB9A0BF99 Uptime: 23:08:09 up 1 min, 1 user, load average: 1.44, 0.51, 0.18 ubnt@ubnt:~$ logout Connection to 192.168.1.1 closed.