2019年1月8日火曜日

Django debug -toolbar のインストール

$ pip3 install django-debug-toolbar
$ vi Project/urls.py  <<__EOF__
from django.conf import settings
from django.conf.urls import include, url

if settings.DEBUG:
    import debug_toolbar
    urlpatterns += [
        url(r'^__debug__/', include(debug_toolbar.urls)),
    ]
__EOF__
$ vi Project/settings.py  <<__EOF__
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',  # これがあることを確認(なければ追加)
    'debug_toolbar',  # 追加
    ]
MIDDLEWARE = [
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'debug_toolbar.middleware.DebugToolbarMiddleware',  # 追加
]

# Debug Toolbar

DEBUG = True

if DEBUG:
    INTERNAL_IPS = ['127.0.0.1', 'localhost']

    def custom_show_toolbar(request):
        return True

    DEBUG_TOOLBAR_PANELS = [
        'debug_toolbar.panels.timer.TimerPanel',
        'debug_toolbar.panels.request.RequestPanel',
        'debug_toolbar.panels.sql.SQLPanel',
        'debug_toolbar.panels.templates.TemplatesPanel',
        'debug_toolbar.panels.cache.CachePanel',
        'debug_toolbar.panels.logging.LoggingPanel',
    ]

    DEBUG_TOOLBAR_CONFIG = {
        'INTERCEPT_REDIRECTS': False,
        'SHOW_TOOLBAR_CALLBACK': custom_show_toolbar,
        'HIDE_DJANGO_SQL': False,
        'TAG': 'div',
        'ENABLE_STACKTRACES': True,
    }
__EOF__
$ python36 manage.py collectstatic
$ mv assets/debug_toolbar static/
$ rm -r assets
これで完了

2019年1月7日月曜日

Django データベースをmysql に変更

# pip3 install pymysql
# pip3 install mysql-connector-python
# pip3 freeze -l # <--インストールモジュールの確認
cx-Oracle==7.0.0
Django==2.1.5
django-crispy-forms==1.7.2
django-filter==2.0.0
et-xmlfile==1.0.1
jdcal==1.4
mod-wsgi==4.6.5
mod-wsgi-httpd==2.4.35.1
mysql-connector-python==8.0.13
openpyxl==2.5.12
protobuf==3.6.1
PyMySQL==0.9.3
pytz==2018.5
six==1.12.0

$ vi config/settings.py
DATABASES = {
   'default': {
      'ENGINE': 'django.db.backends.mysql',
      'NAME': 'django', # 作成したデータベース名 予め空DBを作成しておく。
      'USER': 'admin',
      'PASSWORD':'パスワード',
      'HOST': '',
      'PORT': '',
   }
}
$ vi manage.py
import pymysql
pymysql.install_as_MySQLdb()

$ mysql -u admin -p
mysql> create database django;
mysql> quit
$ python36 manage.py makemigrations
$ python36 manage.py migrate
$ python36 manage.py createsuperuser
$ python36 manage.py runserver

※下記エラーが発生。
File "/usr/local/lib64/python3.6/site-packages/pymysql/_auth.py", line 142, in sha2_rsa_encrypt
    raise RuntimeError("cryptography is required for sha256_password or caching_sha2_password")
RuntimeError: cryptography is required for sha256_password or caching_sha2_password

→mysql8にmysql_native_passwordの新しいユーザを作成。
https://wasurenaiyounikaitoko.blogspot.com/2018/10/centos7-mysql.html

django使ってみた。

# yum install python36
$ python36 --version
Python 3.6.6
$ python36
Python 3.6.6 (default, Aug 13 2018, 18:24:23)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> django.get_version()
'2.1.5'

$ mkdir Django
$ cd Django
$ django-admin startproject Project
$ cd Project
$ python36 manage.py startapp Login
$ python36 manage.py startapp app
$ vi Project/settings.py  <<__EOF__
INSTALLED_APPS = [
   .
   .
  'Login',             # <--追加
]
TEMPLATES = [
    { 
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, "templates")],
        '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',
            ],
        },
    },
]
__EOF__

■DBをmysqlに変更
$ vi Project/settings.py  <<__EOF__
DATABASES = {
   'default': {
      'ENGINE': 'django.db.backends.mysql',
      'NAME': 'django', # 作成したデータベース名 予め空DBを作成しておく。
      'USER': 'admin',
      'PASSWORD':'パスワード',
      'HOST': '',
      'PORT': '',
   }
}
__EOF__
$ vi manage.py
import pymysql
pymysql.install_as_MySQLdb()

$ mysql -u admin -p
mysql> create database django;
mysql> quit

$ python36 manage.py makemigrations Login
$ python36 manage.py migrate
$ python36 manage.py createsuperuser
$ python36 manage.py runserver

$ python36 manage.py shell                # <-DB操作

■css, javascriptは、BootStrapを利用。
ダウンロードして、static/bootstrap/下に配置。(admin 2を利用)
https://startbootstrap.com/template-categories/all/

$ mkdir static       #  ~/Django/Project下
$ (cd static;unzip ../../startbootstrap-sb-admin-2-gh-pages.zip)
$ (cd static;ln -s startbootstrap-sb-admin-2-gh-pages bootstrap)
$ (cd static/bootstrap;ls | grep -v -E '^dist$|^js$|^vendor$'| xargs rm -r)
$ mkdir templates
$ vi templates/base.html  <<__EOF__
<!DOCTYPE html>
<html lang="ja">
<head>
{% load staticfiles %}
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>{% block title %}{% endblock %}</title>
<link href="{% static 'bootstrap/vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet">
<link href="{% static 'bootstrap/vendor/metisMenu/metisMenu.min.css' %}" rel="stylesheet">
<link href="{% static 'bootstrap/dist/css/sb-admin-2.css' %}" rel="stylesheet">
<link href="{% static 'bootstrap/vendor/font-awesome/css/font-awesome.min.css' %}" rel="stylesheet" type="text/css">
<link href="{% static 'app/css/structure.css' %}" rel="stylesheet" type="text/css">
<script type="text/javascript" src="{% static 'bootstrap/vendor/jquery/jquery.min.js' %}"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.0/jquery-ui.min.js"></script>
<script src="{% static 'bootstrap/vendor/bootstrap/js/bootstrap.min.js' %}"></script>
<script src="{% static 'bootstrap/vendor/metisMenu/metisMenu.min.js' %}"></script>
<script src="{% static 'bootstrap/vendor/datatables/js/jquery.dataTables.min.js' %}"></script>
<script src="{% static 'bootstrap/vendor/datatables-plugins/dataTables.bootstrap.min.js' %}"></script>
<script src="{% static 'bootstrap/vendor/datatables-responsive/dataTables.responsive.js' %}"></script>
<script src="{% static 'bootstrap/dist/js/sb-admin-2.js' %}"></script>

<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div id="wrapper">
<nav class="navbar navbar-default navbar-static-top manager-nav no-margin" role="navigation">
<div class="navbar-header">
<a class="navbar-brand">gragragrao Company</a>
</div>
<div class="navbar-default sidebar" role="navigation">
<div class="sidebar-nav navbar-collapse">
<ul class="nav" id="side-menu">
<li><a href="/worker_list/"><i class="fa fa-bar-chart" aria-hidden="true"></i> Worker一覧</a></li>
</ul>
</div>
</div>
</nav>
{% block body %}
{% endblock %}
</div>
</body>
</html>
__EOF__
$ vi templates/worker_list.html  <<__EOF__
{% extends "base.html" %}
{% block title %}Worker List{% endblock %}
{% load staticfiles %}
{% block body %}
<div id="wrapper">
<div id="page-wrapper">
<div class="row">
<div class="col-lg-6 full-width margin-top-20percent" >
<div class="panel panel-default full-width">
<div class="panel-heading">
Edit Help
</div>
<div class="panel-body full-width full-height">
<table id="worker-list-table" class="table table-striped table-bordered table-hover dataTable no-footer dtr-inline full-width">
<thead>
<tr>
<th>ID</th>
<th>名前</th>
<th>性別</th>
<th>誕生日</th>
</tr>
</thead>
<tbody>
{% for worker in workers %}
<tr>
<td>{{worker.id}}</td>
<td>{{worker.person.name}}</td>
<td>{{worker.person.sex}}</td>
<td>{{worker.person.birthday}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$('#worker-list-table').DataTable({
responsive: true,
// sort機能の無効化
ordering: false,
// ページの表示件数を変更する
displayLength: 20,
});
});
</script>
{% endblock %}
__EOF__
$ vi Project/settings.py  <<__EOF__
# Static file settings
STATIC_ROOT = os.path.join(BASE_DIR, 'assets')

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
)
__EOF__
$ mkdir static/app
$ mkdir static/app/css
$ vi static/app/css/structure.css  <<__EOF__
* ---------------------------------------------------------- */
/* general */
/* ---------------------------------------------------------- */

.full-height {
    height: 100%;
}

.full-width {
    width: 100%;
}

.margin-top-20percent {
    margin-top: 20px;
}

.no-margin {
    margin: 0 !important;
}
__EOF__

■ディレクトリ構造
Django
├── Project
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-36.pyc
│   │   ├── settings.cpython-36.pyc
│   │   └── urls.cpython-36.pyc
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── app
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-36.pyc
│   │   ├── admin.cpython-36.pyc
│   │   └── models.cpython-36.pyc
│   ├── admin.py
│   ├── apps.py
│   ├── migrations
│   │   ├── __init__.py
│   │   └── __pycache__
│   │       └── __init__.cpython-36.pyc
│   ├── models.py
│   ├── tests.py
│   └── views.py
├── manage.py
├── static
│   ├── app
│   │   └── css
│   │       └── structure.css
│   ├── bootstrap
│       ├── dist
│       ├── js
│       └── vendor
└── templates
    ├── base.html
    └── worker_list.html


※参考
https://qiita.com/gragragrao/items/373057783ba8856124f3
https://github.com/gragragrao/manager_project


※ログインを実装したところエラーが発生。
$ python36 manage.py makemigrations
   .
   .
from django.contrib.auth.views import login
ImportError: cannot import name 'login'

->django 2.1から login はloginViewに変わったらしい。

from django.contrib.auth.view import login
from django.contrib.auth import logout
     ↓
from django.contrib.auth.views import ( LoginView, LogoutView )


※マイグレーションでエラーがでた。
$ python36 manage.py makemigrations
You are trying to add a non-nullable field 'identifier' to person without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
 2) Quit, and let me add a default in models.py
Select an option: 2

-> app/migrations/配下のファイルを削除


Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

->hijack

※ログイン実行でエラー
if self.request.user.is_authenticated():
TypeError: 'bool' object is not callable

->djangoの古いバージョンでは、methodであったが、今は属性。

request.user.is_authenticated():
    ↓
request.user.is_authenticated:


















シャットダウン時の後処理 (shutdown)

# vi /etc/systemd/system/drop.service [Unit] Description= stop httpgwd DefaultDependencies=no Before=shutdown.target RefuseManualStart=true ...