LoginSignup
1
0

More than 3 years have passed since last update.

Django girls-3 作業フロー

Last updated at Posted at 2020-03-04

PythonAnywhereのアカウント作成

www.pythonanywhere.com
Djangohkp

新プロジェクトの作成

django-admin startproject mysite .
.はカレントディレクトリにDjangoをインストールする
*SpyderのIPコンソールでは実行されなかった。コンソールに直接入力しなければならない。

設定変更

編集したファイル:settings.py
タイムゾーンの変更
TIME_ZONE = 'Asia/Tokyo'

言語の変更
LANGUAGE_CODE = 'ja'

静的ファイルのパスの追加
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

ホストにpythonanywhere.comを追加
ALLOWED_HOSTS = ['127.0.0.1', '.pythonanywhere.com']

DEBUG が True に設定されていて、ALLOWED_HOSTS が空のリストの時は、自動的に ['localhost', '127.0.0.1', '[::1]'] という3つのホストに対してチェックが行われます。 このままの設定では、これから私たちがデプロイして使う PythonAnywhere のホストネームが含まれていません。

データベースのセットアップ

デフォルトでSQlite3が設定されている
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
コンソール上で以下のコマンドを実行
python manage.py migrate

Webサーバの起動

python manage.py runserver

以下のアドレスで接続確認
http://127.0.0.1:8000/

*Webサーバ起動時にはコマンドプロンプトがwebサーバの実行環境になっているため、並列しながらコマンドを入力する場合は新たにコマンドラインを立ち上げる。
デフォルトのコマンドプロンプトから仮想環境に遷移する方法がわからなかったので、Anacondaからコンソールを立ち上げた。

Djangoモデルの作成

新しいアプリケーションの作成

1.python manage.py startapp blog
2.setting.pyに項目を追加する。
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog.apps.BlogConfig',
]
3.models.pyにブログポストモデルを定義する。
以下の設定を書き込む
from django.conf import settings
from django.db import models
from django.utils import timezone

class Post(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)

  def publish(self):
self.published_date = timezone.now()
self.save()

def __str__(self):
    return self.title

参考サイトhttps://docs.djangoproject.com/ja/2.2/ref/models/fields/#field-types

データベースにモデルのためのテーブルを作成する

python manage.py makemigrations blog

実行結果
Migrations for 'blog':
blog/migrations/0001_initial.py:

  • Create model Post

python manage.py migrate blog
実行結果
Operations to perform:
Apply all migrations: blog
Running migrations:
Applying blog.0001_initial... OK

adminの登録

1.blog/admin.pyの内容を書き換える
from django.contrib import admin
from .models import Post

admin.site.register(Post)
2.python manage.py runserver を実行
3.http://127.0.0.1:8000/admin/にアクセス
4.python manage.py createsuperuser を実行
5.ユーザー名などを登録
6.ログイン試行

~中略~

デプロイ

Pythonanywhereの設定

1.PythonanywhereのBashコンソールを起動
2.PythonAnywhere Bash command-lineに以下のコマンドを入力

pip3.7 install --user pythonanywhere

*原文では3.6を指定していたが、エラーが出たので3.7に変更した。
3.
*<>内は任意のPythonAnywhereアカウント、<>は不要

pa_autoconfigure_django.py --python=3.6 https://github.com/<your-github-username>/my-first-blog.git

実行結果

< Running API sanity checks >
   \
    ~<:>>>>>>>>>
Cloning into '/home/djangohkp/djangohkp.pythonanywhere.com'...
remote: Enumerating objects: 29, done.
remote: Counting objects: 100% (29/29), done.
remote: Compressing objects: 100% (22/22), done.
remote: Total 29 (delta 3), reused 29 (delta 3), pack-reused 0
Unpacking objects: 100% (29/29), done.
Checking connectivity... done.
< Creating virtualenv with Python3.6 >
   \
    ~<:>>>>>>>>>
Running virtualenv with interpreter /usr/bin/python3.6
Already using interpreter /usr/bin/python3.6
Using base prefix '/usr'
New python executable in /home/djangohkp/.virtualenvs/djangohkp.pythonanywhere.com/bin/python3.6
Also creating executable in /home/djangohkp/.virtualenvs/djangohkp.pythonanywhere.com/bin/python
Installing setuptools, pip, wheel...
done.
virtualenvwrapper.user_scripts creating /home/djangohkp/.virtualenvs/djangohkp.pythonanywhere.com/b
in/predeactivate
virtualenvwrapper.user_scripts creating /home/djangohkp/.virtualenvs/djangohkp.pythonanywhere.com/b
in/postdeactivate
virtualenvwrapper.user_scripts creating /home/djangohkp/.virtualenvs/djangohkp.pythonanywhere.com/b
in/preactivate
virtualenvwrapper.user_scripts creating /home/djangohkp/.virtualenvs/djangohkp.pythonanywhere.com/b
in/postactivate
virtualenvwrapper.user_scripts creating /home/djangohkp/.virtualenvs/djangohkp.pythonanywhere.com/bin/get_env_details

  ___________________________________________________________________
/                                                                     \
| Pip installing -r                                                   |
| /home/djangohkp/djangohkp.pythonanywhere.com/requirements.txt (this |
| may take a couple of minutes)                                       |
\                                                                     /
  -------------------------------------------------------------------
   \
    ~<:>>>>>>>>>
Looking in links: /usr/share/pip-wheels
Collecting Django~=2.2.4
  Downloading Django-2.2.11-py3-none-any.whl (7.5 MB)
     |████████████████████████████████| 7.5 MB 21.4 MB/s 
Processing /usr/share/pip-wheels/pytz-2019.3-py2.py3-none-any.whl
Collecting sqlparse
  Downloading sqlparse-0.3.1-py2.py3-none-any.whl (40 kB)
     |████████████████████████████████| 40 kB 973 kB/s 
Installing collected packages: pytz, sqlparse, Django
dSuccessfully installed Django-2.2.11 pytz-2019.3 sqlparse-0.3.1

< Creating web app via API >
   \
    ~<:>>>>>>>>>

< Adding static files mappings for /static/ and /media/ >
   \
    ~<:>>>>>>>>>

< Updating wsgi file at /var/www/djangohkp_pythonanywhere_com_wsgi.py >
   \
    ~<:>>>>>>>>>

< Updating settings.py >
   \
    ~<:>>>>>>>>>
< Running collectstatic >
   \
    ~<:>>>>>>>>>

119 static files copied to '/home/djangohkp/djangohkp.pythonanywhere.com/static'.

< Running migrate database >
   \
    ~<:>>>>>>>>>
Operations to perform:
  Apply all migrations: admin, auth, blog, 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 blog.0001_initial... OK
  Applying sessions.0001_initial... OK

< Reloading djangohkp.pythonanywhere.com via API >
   \
    ~<:>>>>>>>>>

  ____________________________________
/                                      \
| All done!  Your site is now live at  |
| https://djangohkp.pythonanywhere.com |
\                                      /
  ------------------------------------
   \
    ~<:>>>>>>>>>


  ___________________________________________________________________
/                                                                     \
| Starting Bash shell with activated virtualenv in project directory. |
| Press Ctrl+D to exit.                                               |
\                                                                     /
  -------------------------------------------------------------------
   \
    ~<:>>>>>>>>>

4.管理者アカウントの初期化
PythonAnywhere上のデータベースと、ローカルPCのデータベースは別のものなので、こちらにも管理者アカウントを登録する。ローカルでのアカウントと同じにするのが良い。

5.作成したWebページにアクセスしてみる
http://.pythonanywhere.com/admin/

web開発のワークフロー
ローカルで変更→DitHubにプッシュ→webサーバーが変更をプル

本番環境ではこれに加えてセキュリティの追加設定が必要
参考ページ https://docs.djangoproject.com/ja/2.2/howto/deployment/checklist/

Djangoビュー

・ビューの概要について(原文引用)
ビュー はアプリのロジックを書いていくところです。 ビューは、以前あなたが作った モデル に情報を要求し、それを テンプレート に渡します。 テンプレートは、次の章で作ります。 ビューはただのPythonの関数です。

1.blog/views.py に追加

def post_list(request):
    return render(request, 'blog/post_list.html', {})

2.http://127.0.0.1:8000/  にアクセス
TemplateDoesNotExist at/ のエラーが表示される

HTMLの編集

  1. blogフォルダにtemplatesフォルダを、更にその中にblogフォルダを作成する。
  2. blog/template/blog にpost_list.html を作成する。
  3. http://127.0.0.1:8000/ にアクセス
  4. 空白のhtmlが表示されれば成功
  5. htmlの編集

GitHubにコードをプッシュする

1.作業ディレクトリでgitを実行する
command-line

git status

2.gitに対してディレクトリ内の変更を全て反映させる

git add --all.

3.アップロードのチェック(アップロードする全ファイルは緑で表示される)

git status

4.変更履歴にコメントを残す(コメントはGithubにも反映される)

git commit -m "コメントの内容"

5.Githubにアップロード(プッシュ)

git push

新しいコードをPythonanywhereにpullする

1.PythonanywhereのBashコンソールで以下を実行する。

cd ~/<your-pythonanywhere-domain>.pythonanywhere.com
git pull

2.Pythonanywhereのホームページから「web」タブに移動して、Reloadすると、アプリが更新される。

CSS

作成したCSSの変更が反映されない。要検証

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0