• Skip to main content
  • Skip to primary sidebar

学習記録

Django

allauthでユーザー登録

2021年5月24日 by 河副 太智 Leave a Comment

アプリ追加

python manage.py startapp accounts

settingsにアプリ追加

‘accounts.apps.AccountsConfig’,

accounts.models.pyに追加

from django.contrib.auth.models import AbstractUser

class CustomUser(AbstractUser):
“””拡張ユーザーモデル”””

class Meta:
verbose_name_plural = ‘CustomUser’

settings.pyに追加

AUTH_USER_MODEL = ‘accounts.CustomUser’

accounts/admin.pyに追加

from django.contrib import admin

from .models import CustomUser

admin.site.register(CustomUser)

django-allauthをインストール
pip install django-allauth

マイグレーション
python manage.py makemigrations
python manage.py migrate

マイグレーションできない場合
以下のようなエラーがでる場合
conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError

settings.pyのdatabaseのdefaultをsqlite3に戻す

1
2
3
4
5
6
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

  1. Delete the DB(settings.pyのdatabaseのdefaultをsqlite3に戻す)
  2. Delete pycache and migrations from all the apps
  3. Make sure you have set AUTH_USER_MODEL
  4. Make migrations

ソース

settings.pyに追記

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'db.apps.DbConfig',
    'django.contrib.postgres',
    'accounts.apps.AccountsConfig',
 
    'django.contrib.sites',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
]

更にsettings.pyに追記

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# django-allauthで利用するdjango.contrib.sitesを使うためにサイト識別用IDを設定
SITE_ID = 1
 
AUTHENTICATION_BACKENDS = (
    'allauth.account.auth_backends.AuthenticationBackend',  # 一般ユーザー用(メールアドレス認証)
    'django.contrib.auth.backends.ModelBackend',  # 管理サイト用(ユーザー名認証)
)
 
# メールアドレス認証に変更する設定
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_USERNAME_REQUIRED = False
 
# サインアップにメールアドレス確認を挟むよう設定
ACCOUNT_EMAIL_VERIFICATION = 'mandatory'
ACCOUNT_EMAIL_REQUIRED = True
 
# ログイン/ログアウト後の遷移先を設定
LOGIN_REDIRECT_URL = 'diary:index'
ACCOUNT_LOGOUT_REDIRECT_URL = 'account_login'
 
# ログアウトリンクのクリック一発でログアウトする設定
ACCOUNT_LOGOUT_ON_GET = True

 

adminページにアクセスできない場合

adminページにアクセスすると以下のようなエラーが出る場合がある
リレーション “django_site”は存在しませんLINE 1:
… “django_site”。 “domain”、 “django_site”。 “name” FROM “django_si …

その際は以下のマイグレーションを行う ソース

1
2
./manage.py migrate sites
./manage.py migrate

リレーションaccounts_customuserが存在しないエラー

マイグレーションすると「django.db.utils.ProgrammingError: リレーション”accounts_customuser”は存在しません」というエラーが出る場合は
python manage.py makemigrations accountsを実行して、それでも
エラーが出たら以下を実行

①settings.pyのINSTALLED_APPSの一番上の’django.contrib.admin’,をコメントアウト
②メインのurl.pyのurlpatternのpath(‘admin/’, admin.site.urls),をコメントアウト
③python manage.py makemigrations
④python manage.py migrate
ソース

マイグレーション時にprimary keyワーニング

マイグレーション時にaccount.EmailAddress: (models.W042) Auto-created primary key used when not defining a primary key type, by default ‘django.db.models.AutoField’.という警告が出たらsettings.pyに

DEFAULT_AUTO_FIELD=’django.db.models.AutoField’
を入れて再度マイグレーションを行う

各種認証関連ページのテンプレートとメール定型文の場所

〇ローカルの場合
\Lib\site-packages\allauth\templates\account
〇AWSの場合
/home/app_admin/venv_ruling/lib/python3.7/site-packages/allauth/templates/account

URLは以下でアクセスできる(サインアップの例)
http://localhost:8000/accounts/signup/

ConnectionRefusedError at /accounts/login/が出たら

以下をsettings.pyに追加

EMAIL_BACKEND = ‘django.core.mail.backends.console.EmailBackend’
ACCOUNT_EMAIL_VERIFICATION = “none”

 

Filed Under: Django

GETクエリーパラメーターの設定

2020年7月30日 by 河副 太智 Leave a Comment

クエリーのパラメーターに応じてレスポンスが変化

クエリ例 http://localhost:8000/hello/?msg=123&msg2=456

1
2
3
4
5
6
7
8
def top(request):
    if 'msg' in request.GET:
        msg = request.GET['msg']
        msg2 = request.GET['msg2']
        return HttpResponse('you typed: "'+ msg +'and'+ msg2 )
    else:
        result = 'please sen msg parameter'
    return HttpResponse(result)

ページにアクセスすると

you typed: “123and456

と表示

Filed Under: Django

Djangoデプロイ

2020年7月29日 by 河副 太智 Leave a Comment

indexページの作成

とりあえず簡単にindexページが表示されるだけのdjangoアプリをデプロイする。

プロジェクトを”Django_app”
アプリを”hello”で作成

Django_app/urls.py

1
2
3
4
5
6
7
8
9
10
from django.contrib import admin
from django.urls import path,include
import hello.views as hello
 
 
urlpatterns = [
    path("", hello.index, name="index"),
    path('admin/', admin.site.urls),
    path('hello/', include('hello.urls')),
]

hello/views.py

1
2
3
4
5
6
7
8
9
from django.shortcuts import render
from django.http import HttpResponse
 
 
def index(request):
    return HttpResponse("indexページ")
 
def top(request):
    return HttpResponse("Helloトップ")

hello/urls.py

1
2
3
4
5
6
from django.urls import path
from . import views
 
urlpatterns = [
    path('', views.top, name='top'),
]

Django_app/setting.py

一旦データベースの設定は全てコメントアウトする。
ロガーの出力先のフォルダはmkdirで作る

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
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__)))
 
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '$k@0dyh#ccb=(@s161+#b*oxp3m)%4iy#7ym*5l@wd9b*c3gj_'
 
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
 
ALLOWED_HOSTS = ['(ここにIPアドレス)', 'localhost']
#localhostを一緒に入れればローカルでも動かせる
 
# Application definition
 
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]
 
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
 
ROOT_URLCONF = 'django_app.urls'
 
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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',
            ],
        },
    },
]
 
WSGI_APPLICATION = 'django_app.wsgi.application'
 
 
# データベース設定
# DATABASES = {
#     'default': {
#         'ENGINE': 'django.db.backends.postgresql_psycopg2',
#         'NAME': 'django_app',
#         'USER': os.environ.get('DB_USER'),
#         'PASSWORD': os.environ.get('DB_PASSWORD'),
#         'HOST': '',
#         'PORT': '',
#     }
# }
 
 
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
 
AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]
 
 
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
 
LANGUAGE_CODE = 'en-us'
 
TIME_ZONE = 'UTC'
 
USE_I18N = True
 
USE_L10N = True
 
USE_TZ = True
 
 
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
 
STATIC_URL = '/static/'
 
 
#  ロギング
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
 
    # ロガーの設定
    'loggers': {
        # Djangoが利用するロガー
        'django': {
            'handlers': ['file'],
            'level': 'INFO',
        },
        # diaryアプリケーションが利用するロガー
        'diary': {
            'handlers': ['file'],
            'level': 'INFO',
        },
    },
 
    # ハンドラの設定
    'handlers': {
        'file': {
            'level': 'INFO',
            'class': 'logging.handlers.TimedRotatingFileHandler',
            'filename': os.path.join(BASE_DIR, 'django_app/logs/django.log'),
            'formatter': 'prod',
            'when': 'D',  # ログローテーション(新しいファイルへの切り替え)間隔の単位(D=日)
            'interval': 1,  # ログローテーション間隔(1日単位)
            'backupCount': 7,  # 保存しておくログファイル数
        },
    },
 
    # フォーマッタの設定
    'formatters': {
        'prod': {
            'format': '\t'.join([
                '%(asctime)s',
                '[%(levelname)s]',
                '%(pathname)s(Line:%(lineno)d)',
                '%(message)s'
            ])
        },
    }
}

/etc/nginx/nginx.conf

静的ファイルとメディアファイルはアプリケーションサーバーの負担を
減らす為にwebサーバーから返す事もできる。

現時点ではアプリケーションサーバーから静的ファイルを返しているが
webサーバーから返す場合は/usr/share/nginx/html/staticと
/usr/share/nginx/html/mediaフォルダを作成してsudo vi /etc/nginx/nginx.confで
コメントアウトしているlocation /staticとlocation /mediaを有効化する。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/
 
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
 
# Load dynamic modules. See /usr/share/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;
 
events {
    worker_connections 1024;
}
 
http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
 
    access_log  /var/log/nginx/access.log  main;
 
    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;
 
    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;
 
    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;
    server {
        listen       80;
        server_name  3.129.28.206;
        root         /usr/share/nginx/html;
 
        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;
 
        #location /static {
        #  alias /usr/share/nginx/html/static;
        #}
 
        #location /media {
        #  alias /usr/share/nginx/html/media;
        #}
 
        location / {
          proxy_set_header Host $http_host;
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
          proxy_set_header X-Forwarded-Proto $scheme;

/etc/nginx/nginx.conf

コマンド”vi ~/.bash_profile”で内容を変更し”source ~/.bashrc”で更新する

1
2
3
4
5
6
7
8
9
10
11
# User specific environment and startup programs
 
PATH=$PATH:$HOME/.local/bin:$HOME/bin
 
export PATH
export DB_USER=******
export DB_PASSWORD=******
export DJANGO_SETTINGS_MODULE=django_app.settings
export ALLOWED_HOSTS=3.129.**.***
export AWS_SES_ACCESS_KEY_ID='AKI***UHEC5VDL******'
export AWS_SES_SECRET_ACCESS_KEY='VjVpxDDDu8**oSLkOXtlVENuKSQeBRp****'

 

 

Filed Under: Django

Djangoロギングの設定

2020年7月29日 by 河副 太智 Leave a Comment

logsという名称のフォルダを作成

settings.pyにて定義してある出力先と同じ場所にフォルダ作成
フォルダの位置がずれるとエラーになるので注意
‘filename’: os.path.join(BASE_DIR, ‘django_app/logs/django.log’),

1
mkdir ~venv_django_app/django_app/django_app/logs

 

ロギングをsettings.pyに設置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#  ロギング
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
 
    # ロガーの設定
    'loggers': {
        # Djangoが利用するロガー
        'django': {
            'handlers': ['file'],
            'level': 'INFO',
        },
        # diaryアプリケーションが利用するロガー
        'diary': {
            'handlers': ['file'],
            'level': 'INFO',
        },
    },
 
    # ハンドラの設定
    'handlers': {
        'file': {
            'level': 'INFO',
            'class': 'logging.handlers.TimedRotatingFileHandler',
            'filename': os.path.join(BASE_DIR, 'django_app/logs/django.log'),
            'formatter': 'prod',
            'when': 'D',  # ログローテーション(新しいファイルへの切り替え)間隔の単位(D=日)
            'interval': 1,  # ログローテーション間隔(1日単位)
            'backupCount': 7,  # 保存しておくログファイル数
        },
    },
 
    # フォーマッタの設定
    'formatters': {
        'prod': {
            'format': '\t'.join([
                '%(asctime)s',
                '[%(levelname)s]',
                '%(pathname)s(Line:%(lineno)d)',
                '%(message)s'
            ])
        },
    }
}

 

Filed Under: Django

Djangoのindexページを作成

2020年7月29日 by 河副 太智 Leave a Comment

indexページの作成

プロジェクトを”Django_app”
アプリを”hello”で作成

Django_app/urls.py

urls.pyはプロジェクトフォルダーにあるがビュー処理はhelloアプリ内で実行

Django_app/urls.py
1
2
3
4
5
6
7
from django.contrib import admin
from django.urls import path,include
<span style="color: #0000ff;">import hello.views as hello</span>
 
urlpatterns = [
    path("", <span style="color: #0000ff;">hello</span>.<span style="color: #ff0000;">index</span>, name="index"),
]

hello/views.py

1
2
3
4
5
from django.shortcuts import render
from django.http import HttpResponse
 
def <span style="color: #ff0000;">index</span>(request):
    return HttpResponse("indexページ")

index以外のページの作成

urlの末尾に”admin”と”hello”がつく場合でhelloはinclude関数を使い、
helloアプリ内でurlとビューの処理を行う

Django_app/urls.py

1
2
3
4
5
6
7
8
9
10
from django.contrib import admin
from django.urls import path,include
<span style="color: #ff0000;">import hello.views as hello</span>
 
 
urlpatterns = [
    path("", hello.index, name="index"),
    path('admin/', admin.site.urls),
    path('hello/', <span style="color: #ff0000;">include('hello.urls')</span>),
]

hello/urls.py

1
2
3
4
5
6
from django.urls import path
from . import views
 
urlpatterns = [
    path('', views.<span style="color: #0000ff;">top</span>, name='top'),
]

hello/views.py

1
2
3
4
5
6
7
8
9
from django.shortcuts import render
from django.http import HttpResponse
 
def index(request):
    return HttpResponse("indexページ")
# Create your views here.
 
def <span style="color: #0000ff;">top</span>(request):
    return HttpResponse("Helloトップ")

 

 

 

 

Filed Under: Django

  • « Go to Previous Page
  • Page 1
  • Page 2

Primary Sidebar

カテゴリー

  • AWS
  • Bootstrap
  • Dash
  • Django
  • flask
  • GIT(sourcetree)
  • Plotly/Dash
  • VPS
  • その他tool
  • ブログ
  • プログラミング
    • Bokeh
    • css
    • HoloViews
    • Jupyter
    • Numpy
    • Pandas
    • PosgreSQL
    • Python 基本
    • python3
      • webアプリ
    • python3解説
    • scikit-learn
    • scipy
    • vps
    • Wordpress
    • グラフ
    • コマンド
    • スクレイピング
    • チートシート
    • データクレンジング
    • ブロックチェーン
    • 作成実績
    • 時系列分析
    • 機械学習
      • 分析手法
      • 教師有り
    • 異常値検知
    • 自然言語処理
  • 一太郎
  • 数学
    • sympy
      • 対数関数(log)
      • 累乗根(n乗根)
    • 暗号学

Copyright © 2025 · Genesis Sample on Genesis Framework · WordPress · Log in