2019年1月7日月曜日

django使ってみた。

# dnf  install python3 python3-libs python3-devel
# python3 -m ensurepip 
$ python3 --version
Python 3.9.18
$ mkdir Django
$ cd Django
$ django-admin startproject Config
$ mv Config Project1
$ cd Project1
$ python3 manage.py startapp app
$ python3 -m venv .venv
$ ln -s ./.venv/lib/python3.9/site-packages 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:


















0 件のコメント:

コメントを投稿

zabbix7 amazon linux2023 インストール postgres15

【postgres】 dnf -y install postgresql15-server postgresql15-server-devel postgresql-setup initdb passwd postgres vi `find / -name pg_hba.con...