1. Setup Environment
1-1. Install Postgresql DB
root@django:/home/ivan# apt-get install postgresql-10
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following additional packages will be installed:
libpq5 libsensors4 postgresql-client-10 postgresql-client-common postgresql-common ssl-cert sysstat
Suggested packages:
lm-sensors locales-all postgresql-doc-10 libjson-perl openssl-blacklist isag
The following NEW packages will be installed:
libpq5 libsensors4 postgresql-10 postgresql-client-10 postgresql-client-common postgresql-common ssl-cert sysstat
0 upgraded, 8 newly installed, 0 to remove and 54 not upgraded.
Need to get 5,327 kB of archives.
After this operation, 20.9 MB of additional disk space will be used.
Do you want to continue? [Y/n]
Get:1 http://kr.archive.ubuntu.com/ubuntu bionic-updates/main amd64 libpq5 amd64 10.10-0ubuntu0.18.04.1 [108 kB]
Get:2 http://kr.archive.ubuntu.com/ubuntu bionic/main amd64 libsensors4 amd64 1:3.4.0-4 [28.8 kB]
Get:3 http://kr.archive.ubuntu.com/ubuntu bionic/main amd64 postgresql-client-common all 190 [29.5 kB]
Get:4 http://kr.archive.ubuntu.com/ubuntu bionic-updates/main amd64 postgresql-client-10 amd64 10.10-0ubuntu0.18.04.1 [935 kB]
Get:5 http://kr.archive.ubuntu.com/ubuntu bionic/main amd64 ssl-cert all 1.0.39 [17.0 kB]
Get:6 http://kr.archive.ubuntu.com/ubuntu bionic/main amd64 postgresql-common all 190 [157 kB]
Get:7 http://kr.archive.ubuntu.com/ubuntu bionic-updates/main amd64 postgresql-10 amd64 10.10-0ubuntu0.18.04.1 [3,758 kB]
Get:8 http://kr.archive.ubuntu.com/ubuntu bionic/main amd64 sysstat amd64 11.6.1-1 [295 kB]
Fetched 5,327 kB in 28s (190 kB/s)
Preconfiguring packages ...
Selecting previously unselected package libpq5:amd64.
(Reading database ... 74383 files and directories currently installed.)
Preparing to unpack .../0-libpq5_10.10-0ubuntu0.18.04.1_amd64.deb ...
Unpacking libpq5:amd64 (10.10-0ubuntu0.18.04.1) ...
Selecting previously unselected package libsensors4:amd64.
Preparing to unpack .../1-libsensors4_1%3a3.4.0-4_amd64.deb ...
Unpacking libsensors4:amd64 (1:3.4.0-4) ...
Selecting previously unselected package postgresql-client-common.
Preparing to unpack .../2-postgresql-client-common_190_all.deb ...
Unpacking postgresql-client-common (190) ...
Selecting previously unselected package postgresql-client-10.
Preparing to unpack .../3-postgresql-client-10_10.10-0ubuntu0.18.04.1_amd64.deb ...
Unpacking postgresql-client-10 (10.10-0ubuntu0.18.04.1) ...
Selecting previously unselected package ssl-cert.
Preparing to unpack .../4-ssl-cert_1.0.39_all.deb ...
Unpacking ssl-cert (1.0.39) ...
Selecting previously unselected package postgresql-common.
Preparing to unpack .../5-postgresql-common_190_all.deb ...
Adding 'diversion of /usr/bin/pg_config to /usr/bin/pg_config.libpq-dev by postgresql-common'
Unpacking postgresql-common (190) ...
Selecting previously unselected package postgresql-10.
Preparing to unpack .../6-postgresql-10_10.10-0ubuntu0.18.04.1_amd64.deb ...
Unpacking postgresql-10 (10.10-0ubuntu0.18.04.1) ...
Selecting previously unselected package sysstat.
Preparing to unpack .../7-sysstat_11.6.1-1_amd64.deb ...
Unpacking sysstat (11.6.1-1) ...
Processing triggers for ureadahead (0.100.0-21) ...
Setting up ssl-cert (1.0.39) ...
Setting up libpq5:amd64 (10.10-0ubuntu0.18.04.1) ...
Processing triggers for libc-bin (2.27-3ubuntu1) ...
Setting up postgresql-client-common (190) ...
Processing triggers for systemd (237-3ubuntu10.29) ...
Setting up postgresql-common (190) ...
Adding user postgres to group ssl-cert
Creating config file /etc/postgresql-common/createcluster.conf with new version
Building PostgreSQL dictionaries from installed myspell/hunspell packages...
Removing obsolete dictionary files:
Created symlink /etc/systemd/system/multi-user.target.wants/postgresql.service → /lib/systemd/system/postgresql.service.
Setting up libsensors4:amd64 (1:3.4.0-4) ...
Processing triggers for man-db (2.8.3-2ubuntu0.1) ...
Setting up postgresql-client-10 (10.10-0ubuntu0.18.04.1) ...
update-alternatives: using /usr/share/postgresql/10/man/man1/psql.1.gz to provide /usr/share/man/man1/psql.1.gz (psql.1.gz) in auto mode
Setting up sysstat (11.6.1-1) ...
Creating config file /etc/default/sysstat with new version
update-alternatives: using /usr/bin/sar.sysstat to provide /usr/bin/sar (sar) in auto mode
Created symlink /etc/systemd/system/multi-user.target.wants/sysstat.service → /lib/systemd/system/sysstat.service.
Setting up postgresql-10 (10.10-0ubuntu0.18.04.1) ...
Creating new PostgreSQL cluster 10/main ...
/usr/lib/postgresql/10/bin/initdb -D /var/lib/postgresql/10/main --auth-local peer --auth-host md5
The files belonging to this database system will be owned by user "postgres".
This user must also own the server process.
The database cluster will be initialized with locale "en_US.UTF-8".
The default database encoding has accordingly been set to "UTF8".
The default text search configuration will be set to "english".
Data page checksums are disabled.
fixing permissions on existing directory /var/lib/postgresql/10/main ... ok
creating subdirectories ... ok
selecting default max_connections ... 100
selecting default shared_buffers ... 128MB
selecting default timezone ... Etc/UTC
selecting dynamic shared memory implementation ... posix
creating configuration files ... ok
running bootstrap script ... ok
performing post-bootstrap initialization ... ok
syncing data to disk ... ok
Success. You can now start the database server using:
/usr/lib/postgresql/10/bin/pg_ctl -D /var/lib/postgresql/10/main -l logfile start
Ver Cluster Port Status Owner Data directory Log file
10 main 5432 down postgres /var/lib/postgresql/10/main /var/log/postgresql/postgresql-10-main.log
update-alternatives: using /usr/share/postgresql/10/man/man1/postmaster.1.gz to provide /usr/share/man/man1/postmaster.1.gz (postmaster.1.gz) in auto mode
Processing triggers for systemd (237-3ubuntu10.29) ...
Processing triggers for ureadahead (0.100.0-21) ...
Processing triggers for libc-bin (2.27-3ubuntu1) ...
root@django:/home/ivan#
1-2. Install pip
root@django:/home/ivan# pip install psycopg2
Command 'pip' not found, but can be installed with:
apt install python-pip
root@django:/home/ivan# python -m pip install psycopg2
/usr/bin/python: No module named pip
root@django:/home/ivan# apt install python-pip
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following additional packages will be installed:
libpython-all-dev libpython-dev libpython2.7 libpython2.7-dev python-all python-all-dev python-asn1crypto
python-cffi-backend python-crypto python-cryptography python-dbus python-dev python-enum34 python-gi python-idna
python-ipaddress python-keyring python-keyrings.alt python-secretstorage python-setuptools python-six python-wheel
python-xdg python2.7-dev
Suggested packages:
python-crypto-doc python-cryptography-doc python-cryptography-vectors python-dbus-dbg python-dbus-doc python-enum34-doc
python-gi-cairo gnome-keyring libkf5wallet-bin gir1.2-gnomekeyring-1.0 python-fs python-gdata python-keyczar
python-secretstorage-doc python-setuptools-doc
The following NEW packages will be installed:
libpython-all-dev libpython-dev libpython2.7 libpython2.7-dev python-all python-all-dev python-asn1crypto
python-cffi-backend python-crypto python-cryptography python-dbus python-dev python-enum34 python-gi python-idna
python-ipaddress python-keyring python-keyrings.alt python-pip python-secretstorage python-setuptools python-six
python-wheel python-xdg python2.7-dev
0 upgraded, 25 newly installed, 0 to remove and 54 not upgraded.
Need to get 31.2 MB of archives.
After this operation, 53.6 MB of additional disk space will be used.
Do you want to continue? [Y/n]
Get:1 http://kr.archive.ubuntu.com/ubuntu bionic-updates/main amd64 libpython2.7 amd64 2.7.15-4ubuntu4~18.04.2 [1,053 kB]
Get:2 http://kr.archive.ubuntu.com/ubuntu bionic-updates/main amd64 libpython2.7-dev amd64 2.7.15-4ubuntu4~18.04.2 [28.3 MB]
Get:3 http://kr.archive.ubuntu.com/ubuntu bionic/main amd64 libpython-dev amd64 2.7.15~rc1-1 [7,684 B]
Get:4 http://kr.archive.ubuntu.com/ubuntu bionic/main amd64 libpython-all-dev amd64 2.7.15~rc1-1 [1,092 B]
Get:5 http://kr.archive.ubuntu.com/ubuntu bionic/main amd64 python-all amd64 2.7.15~rc1-1 [1,076 B]
Get:6 http://kr.archive.ubuntu.com/ubuntu bionic-updates/main amd64 python2.7-dev amd64 2.7.15-4ubuntu4~18.04.2 [276 kB]
Get:7 http://kr.archive.ubuntu.com/ubuntu bionic/main amd64 python-dev amd64 2.7.15~rc1-1 [1,256 B]
Get:8 http://kr.archive.ubuntu.com/ubuntu bionic/main amd64 python-all-dev amd64 2.7.15~rc1-1 [1,100 B]
Get:9 http://kr.archive.ubuntu.com/ubuntu bionic/main amd64 python-asn1crypto all 0.24.0-1 [72.7 kB]
Get:10 http://kr.archive.ubuntu.com/ubuntu bionic/main amd64 python-cffi-backend amd64 1.11.5-1 [63.4 kB]
Get:11 http://kr.archive.ubuntu.com/ubuntu bionic/main amd64 python-crypto amd64 2.6.1-8ubuntu2 [244 kB]
Get:12 http://kr.archive.ubuntu.com/ubuntu bionic/main amd64 python-enum34 all 1.1.6-2 [34.8 kB]
Get:13 http://kr.archive.ubuntu.com/ubuntu bionic/main amd64 python-idna all 2.6-1 [32.4 kB]
Get:14 http://kr.archive.ubuntu.com/ubuntu bionic/main amd64 python-ipaddress all 1.0.17-1 [18.2 kB]
Get:15 http://kr.archive.ubuntu.com/ubuntu bionic/main amd64 python-six all 1.11.0-2 [11.3 kB]
Get:16 http://kr.archive.ubuntu.com/ubuntu bionic-updates/main amd64 python-cryptography amd64 2.1.4-1ubuntu1.3 [221 kB]
Get:17 http://kr.archive.ubuntu.com/ubuntu bionic/main amd64 python-dbus amd64 1.2.6-1 [90.2 kB]
Get:18 http://kr.archive.ubuntu.com/ubuntu bionic-updates/main amd64 python-gi amd64 3.26.1-2ubuntu1 [197 kB]
Get:19 http://kr.archive.ubuntu.com/ubuntu bionic/main amd64 python-secretstorage all 2.3.1-2 [11.8 kB]
Get:20 http://kr.archive.ubuntu.com/ubuntu bionic/main amd64 python-keyring all 10.6.0-1 [30.6 kB]
Get:21 http://kr.archive.ubuntu.com/ubuntu bionic/main amd64 python-keyrings.alt all 3.0-1 [16.7 kB]
Get:22 http://kr.archive.ubuntu.com/ubuntu bionic-updates/universe amd64 python-pip all 9.0.1-2.3~ubuntu1.18.04.1 [151 kB]
Get:23 http://kr.archive.ubuntu.com/ubuntu bionic/main amd64 python-setuptools all 39.0.1-2 [329 kB]
Get:24 http://kr.archive.ubuntu.com/ubuntu bionic/universe amd64 python-wheel all 0.30.0-0.2 [36.4 kB]
Get:25 http://kr.archive.ubuntu.com/ubuntu bionic/universe amd64 python-xdg all 0.25-4ubuntu1 [31.3 kB]
Fetched 31.2 MB in 2min 22s (220 kB/s)
Selecting previously unselected package libpython2.7:amd64.
(Reading database ... 75194 files and directories currently installed.)
Preparing to unpack .../00-libpython2.7_2.7.15-4ubuntu4~18.04.2_amd64.deb ...
Unpacking libpython2.7:amd64 (2.7.15-4ubuntu4~18.04.2) ...
Selecting previously unselected package libpython2.7-dev:amd64.
Preparing to unpack .../01-libpython2.7-dev_2.7.15-4ubuntu4~18.04.2_amd64.deb ...
Unpacking libpython2.7-dev:amd64 (2.7.15-4ubuntu4~18.04.2) ...
Selecting previously unselected package libpython-dev:amd64.
Preparing to unpack .../02-libpython-dev_2.7.15~rc1-1_amd64.deb ...
Unpacking libpython-dev:amd64 (2.7.15~rc1-1) ...
Selecting previously unselected package libpython-all-dev:amd64.
Preparing to unpack .../03-libpython-all-dev_2.7.15~rc1-1_amd64.deb ...
Unpacking libpython-all-dev:amd64 (2.7.15~rc1-1) ...
Selecting previously unselected package python-all.
Preparing to unpack .../04-python-all_2.7.15~rc1-1_amd64.deb ...
Unpacking python-all (2.7.15~rc1-1) ...
Selecting previously unselected package python2.7-dev.
Preparing to unpack .../05-python2.7-dev_2.7.15-4ubuntu4~18.04.2_amd64.deb ...
Unpacking python2.7-dev (2.7.15-4ubuntu4~18.04.2) ...
Selecting previously unselected package python-dev.
Preparing to unpack .../06-python-dev_2.7.15~rc1-1_amd64.deb ...
Unpacking python-dev (2.7.15~rc1-1) ...
Selecting previously unselected package python-all-dev.
Preparing to unpack .../07-python-all-dev_2.7.15~rc1-1_amd64.deb ...
Unpacking python-all-dev (2.7.15~rc1-1) ...
Selecting previously unselected package python-asn1crypto.
Preparing to unpack .../08-python-asn1crypto_0.24.0-1_all.deb ...
Unpacking python-asn1crypto (0.24.0-1) ...
Selecting previously unselected package python-cffi-backend.
Preparing to unpack .../09-python-cffi-backend_1.11.5-1_amd64.deb ...
Unpacking python-cffi-backend (1.11.5-1) ...
Selecting previously unselected package python-crypto.
Preparing to unpack .../10-python-crypto_2.6.1-8ubuntu2_amd64.deb ...
Unpacking python-crypto (2.6.1-8ubuntu2) ...
Selecting previously unselected package python-enum34.
Preparing to unpack .../11-python-enum34_1.1.6-2_all.deb ...
Unpacking python-enum34 (1.1.6-2) ...
Selecting previously unselected package python-idna.
Preparing to unpack .../12-python-idna_2.6-1_all.deb ...
Unpacking python-idna (2.6-1) ...
Selecting previously unselected package python-ipaddress.
Preparing to unpack .../13-python-ipaddress_1.0.17-1_all.deb ...
Unpacking python-ipaddress (1.0.17-1) ...
Selecting previously unselected package python-six.
Preparing to unpack .../14-python-six_1.11.0-2_all.deb ...
Unpacking python-six (1.11.0-2) ...
Selecting previously unselected package python-cryptography.
Preparing to unpack .../15-python-cryptography_2.1.4-1ubuntu1.3_amd64.deb ...
Unpacking python-cryptography (2.1.4-1ubuntu1.3) ...
Selecting previously unselected package python-dbus.
Preparing to unpack .../16-python-dbus_1.2.6-1_amd64.deb ...
Unpacking python-dbus (1.2.6-1) ...
Selecting previously unselected package python-gi.
Preparing to unpack .../17-python-gi_3.26.1-2ubuntu1_amd64.deb ...
Unpacking python-gi (3.26.1-2ubuntu1) ...
Selecting previously unselected package python-secretstorage.
Preparing to unpack .../18-python-secretstorage_2.3.1-2_all.deb ...
Unpacking python-secretstorage (2.3.1-2) ...
Selecting previously unselected package python-keyring.
Preparing to unpack .../19-python-keyring_10.6.0-1_all.deb ...
Unpacking python-keyring (10.6.0-1) ...
Selecting previously unselected package python-keyrings.alt.
Preparing to unpack .../20-python-keyrings.alt_3.0-1_all.deb ...
Unpacking python-keyrings.alt (3.0-1) ...
Selecting previously unselected package python-pip.
Preparing to unpack .../21-python-pip_9.0.1-2.3~ubuntu1.18.04.1_all.deb ...
Unpacking python-pip (9.0.1-2.3~ubuntu1.18.04.1) ...
Selecting previously unselected package python-setuptools.
Preparing to unpack .../22-python-setuptools_39.0.1-2_all.deb ...
Unpacking python-setuptools (39.0.1-2) ...
Selecting previously unselected package python-wheel.
Preparing to unpack .../23-python-wheel_0.30.0-0.2_all.deb ...
Unpacking python-wheel (0.30.0-0.2) ...
Selecting previously unselected package python-xdg.
Preparing to unpack .../24-python-xdg_0.25-4ubuntu1_all.deb ...
Unpacking python-xdg (0.25-4ubuntu1) ...
Setting up python-idna (2.6-1) ...
Setting up python-setuptools (39.0.1-2) ...
Setting up python-asn1crypto (0.24.0-1) ...
Setting up python-crypto (2.6.1-8ubuntu2) ...
Setting up python-wheel (0.30.0-0.2) ...
Setting up python-cffi-backend (1.11.5-1) ...
Setting up python-gi (3.26.1-2ubuntu1) ...
Setting up python-six (1.11.0-2) ...
Processing triggers for libc-bin (2.27-3ubuntu1) ...
Setting up python-enum34 (1.1.6-2) ...
Setting up libpython2.7:amd64 (2.7.15-4ubuntu4~18.04.2) ...
Processing triggers for man-db (2.8.3-2ubuntu0.1) ...
Setting up libpython2.7-dev:amd64 (2.7.15-4ubuntu4~18.04.2) ...
Setting up python-dbus (1.2.6-1) ...
Setting up python-ipaddress (1.0.17-1) ...
Setting up python-pip (9.0.1-2.3~ubuntu1.18.04.1) ...
Setting up python2.7-dev (2.7.15-4ubuntu4~18.04.2) ...
Setting up python-all (2.7.15~rc1-1) ...
Setting up python-xdg (0.25-4ubuntu1) ...
Setting up libpython-dev:amd64 (2.7.15~rc1-1) ...
Setting up python-dev (2.7.15~rc1-1) ...
Setting up libpython-all-dev:amd64 (2.7.15~rc1-1) ...
Setting up python-keyrings.alt (3.0-1) ...
Setting up python-all-dev (2.7.15~rc1-1) ...
Setting up python-cryptography (2.1.4-1ubuntu1.3) ...
Setting up python-secretstorage (2.3.1-2) ...
Setting up python-keyring (10.6.0-1) ...
Processing triggers for libc-bin (2.27-3ubuntu1) ...
root@django:/home/ivan#
1-3. Install psycopg2
- For postgresql + python
root@django:/home/ivan# pip install psycopg2
Collecting psycopg2
Downloading https://files.pythonhosted.org/packages/84/d7/6a93c99b5ba4d4d22daa3928b983cec66df4536ca50b22ce5dcac65e4e71/psycopg2-2.8.4.tar.gz (377kB)
100% |████████████████████████████████| 378kB 1.2MB/s
Complete output from command python setup.py egg_info:
running egg_info
creating pip-egg-info/psycopg2.egg-info
writing pip-egg-info/psycopg2.egg-info/PKG-INFO
writing top-level names to pip-egg-info/psycopg2.egg-info/top_level.txt
writing dependency_links to pip-egg-info/psycopg2.egg-info/dependency_links.txt
writing manifest file 'pip-egg-info/psycopg2.egg-info/SOURCES.txt'
Error: You need to install postgresql-server-dev-X.Y for building a server-side extension or libpq-dev for building a client-side application.
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-I1znpb/psycopg2/
root@django:/home/ivan#
==> install postgresql server-dev again
root@django:/home/ivan# apt-get install postgresql-server-dev-10
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following additional packages will be installed:
libpq-dev
Suggested packages:
postgresql-doc-10
The following NEW packages will be installed:
libpq-dev postgresql-server-dev-10
0 upgraded, 2 newly installed, 0 to remove and 54 not upgraded.
Need to get 1,054 kB of archives.
After this operation, 7,678 kB of additional disk space will be used.
Do you want to continue? [Y/n]
Get:1 http://kr.archive.ubuntu.com/ubuntu bionic-updates/main amd64 libpq-dev amd64 10.10-0ubuntu0.18.04.1 [218 kB]
Get:2 http://kr.archive.ubuntu.com/ubuntu bionic-updates/universe amd64 postgresql-server-dev-10 amd64 10.10-0ubuntu0.18.04.1 [836 kB]
Fetched 1,054 kB in 5s (228 kB/s)
Selecting previously unselected package libpq-dev.
(Reading database ... 76100 files and directories currently installed.)
Preparing to unpack .../libpq-dev_10.10-0ubuntu0.18.04.1_amd64.deb ...
Unpacking libpq-dev (10.10-0ubuntu0.18.04.1) ...
Selecting previously unselected package postgresql-server-dev-10.
Preparing to unpack .../postgresql-server-dev-10_10.10-0ubuntu0.18.04.1_amd64.deb ...
Unpacking postgresql-server-dev-10 (10.10-0ubuntu0.18.04.1) ...
Setting up libpq-dev (10.10-0ubuntu0.18.04.1) ...
Setting up postgresql-server-dev-10 (10.10-0ubuntu0.18.04.1) ...
Processing triggers for man-db (2.8.3-2ubuntu0.1) ...
- Install psycopg2 again
root@django:/home/ivan# pip install psycopg2
Collecting psycopg2
Using cached https://files.pythonhosted.org/packages/84/d7/6a93c99b5ba4d4d22daa3928b983cec66df4536ca50b22ce5dcac65e4e71/psycopg2-2.8.4.tar.gz
Building wheels for collected packages: psycopg2
Running setup.py bdist_wheel for psycopg2 ... done
Stored in directory: /root/.cache/pip/wheels/7e/5b/53/30085c62689dcfce50c8f40759945a49eb856af082e9ebf751
Successfully built psycopg2
Installing collected packages: psycopg2
Successfully installed psycopg2-2.8.4
root@django:/home/ivan#
2. Setup Database & Django server for the first time
2-1. Create DB
ivan@django:~$ sudo -u postgres createdb myDB
[sudo] password for ivan:
ivan@django:~$ sudo -u postgres psql myDB
psql (10.10 (Ubuntu 10.10-0ubuntu0.18.04.1))
Type "help" for help.
myDB=# create user djuser with password 'sds1234';
CREATE ROLE
myDB=#
myDB=# alter role djuser set client_encoding to 'utf-8';
ALTER ROLE
myDB=# alter role djuser set timezone to 'Asia/Seoul';
ALTER ROLE
myDB=#
myDB=# grant all privileges on database "myDB" to djuser;
GRANT
2-2. Update settup.py
ivan@django:~/djgo/mysite$ vi settings.py
~~
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'myDB',
'USER': 'djuser',
'PASSWORD': 'sds1234',
'HOST': 'localhost',
'PORT': '',
}
}
~~
ALLOWED_HOSTS = ['127.0.0.1','pythonanywhere.com']
~~
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static:')
~~
~~
2-3. Check DB Config
ivan@django:~/djgo$ source djenv/bin/activate
(djenv) ivan@django:~/djgo$
(djenv) ivan@django:~/djgo$ python manage.py migrate
Traceback (most recent call last):
File "/home/ivan/djgo/djenv/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 20, in
import psycopg2 as Database
ModuleNotFoundError: No module named 'psycopg2'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "manage.py", line 15, in
execute_from_command_line(sys.argv)
File "/home/ivan/djgo/djenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
utility.execute()
File "/home/ivan/djgo/djenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 347, in execute
django.setup()
File "/home/ivan/djgo/djenv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/ivan/djgo/djenv/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate
app_config.import_models()
File "/home/ivan/djgo/djenv/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "", line 994, in _gcd_import
File "", line 971, in _find_and_load
File "", line 955, in _find_and_load_unlocked
File "", line 665, in _load_unlocked
File "", line 678, in exec_module
File "", line 219, in _call_with_frames_removed
File "/home/ivan/djgo/djenv/lib/python3.6/site-packages/django/contrib/auth/models.py", line 2, in
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
File "/home/ivan/djgo/djenv/lib/python3.6/site-packages/django/contrib/auth/base_user.py", line 47, in
class AbstractBaseUser(models.Model):
File "/home/ivan/djgo/djenv/lib/python3.6/site-packages/django/db/models/base.py", line 114, in __new__
new_class.add_to_class('_meta', Options(meta, app_label))
File "/home/ivan/djgo/djenv/lib/python3.6/site-packages/django/db/models/base.py", line 315, in add_to_class
value.contribute_to_class(cls, name)
File "/home/ivan/djgo/djenv/lib/python3.6/site-packages/django/db/models/options.py", line 205, in contribute_to_class
self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
File "/home/ivan/djgo/djenv/lib/python3.6/site-packages/django/db/__init__.py", line 33, in __getattr__
return getattr(connections[DEFAULT_DB_ALIAS], item)
File "/home/ivan/djgo/djenv/lib/python3.6/site-packages/django/db/utils.py", line 202, in __getitem__
backend = load_backend(db['ENGINE'])
File "/home/ivan/djgo/djenv/lib/python3.6/site-packages/django/db/utils.py", line 110, in load_backend
return import_module('%s.base' % backend_name)
File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "/home/ivan/djgo/djenv/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 24, in
raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e)
django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2'
- need to install psyscopg2 again on djenv environment
2-4. Install psyscopg2 again in djenv environment
(djenv) ivan@django:~/djgo$ pip install psycopg2
Collecting psycopg2
Downloading https://files.pythonhosted.org/packages/84/d7/6a93c99b5ba4d4d22daa3928b983cec66df4536ca50b22ce5dcac65e4e71/psycopg2-2.8.4.tar.gz (377kB)
|████████████████████████████████| 378kB 835kB/s
Building wheels for collected packages: psycopg2
Building wheel for psycopg2 (setup.py) ... done
Created wheel for psycopg2: filename=psycopg2-2.8.4-cp36-cp36m-linux_x86_64.whl size=419307 sha256=fc8200b1c88f4cfc821e0ec7dddaa70be1b04419a06e394bf7932cf0ba7e75f1
Stored in directory: /home/ivan/.cache/pip/wheels/7e/5b/53/30085c62689dcfce50c8f40759945a49eb856af082e9ebf751
Successfully built psycopg2
Installing collected packages: psycopg2
Successfully installed psycopg2-2.8.4
(djenv) ivan@django:~/djgo$
2-5. Execute migrate again
(djenv) ivan@django:~/djgo$ python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, 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 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 sessions.0001_initial... OK
(djenv) ivan@django:~/djgo$
2-6. Run Django server
(djenv) ivan@django:~/djgo$ python manage.py runserver
Performing system checks...
System check identified no issues (0 silenced).
November 13, 2019 - 20:02:34
Django version 2.0.13, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
==> Error occur on browser (ie)
이 페이지에 연결할 수 없음
다음을 시도해 보세요.
웹 주소가 맞는지 확인하세요. http://192.168.56.200:8000
Bing에서 "http://192.168.56.200:8000" 검색
~~
2-7. Fix the Errors
- Confirm Firewall status
ivan@django:~$ sudo ufw status
Status: inactive
- Change runserver IP/Port
djenv) ivan@django:~/djgo$ python manage.py runserver 0.0.0.0:8000
Performing system checks...
System check identified no issues (0 silenced).
November 14, 2019 - 10:20:28
Django version 2.0.13, using settings 'mysite.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.
- Check listen port
ivan@django:~$ netstat -an | more
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 0.0.0.0:8000 0.0.0.0:* LISTEN <<<<<
- Change browser (ie -> chrome)
DisallowedHost at /
Invalid HTTP_HOST header: '192.168.56.200:8000'. You may need to add '192.168.56.200' to ALLOWED_HOSTS.
Request Method: GET
Request URL: http://192.168.56.200:8000/
Django Version: 2.0.13
Exception Type: DisallowedHost
Exception Value:
Invalid HTTP_HOST header: '192.168.56.200:8000'. You may need to add '192.168.56.200' to ALLOWED_HOSTS.
Exception Location: /home/ivan/djgo/djenv/lib/python3.6/site-packages/django/http/request.py in get_host, line 105
Python Executable: /home/ivan/djgo/djenv/bin/python
Python Version: 3.6.8
Python Path:
['/home/ivan/djgo',
'/usr/lib/python36.zip',
'/usr/lib/python3.6',
'/usr/lib/python3.6/lib-dynload',
'/home/ivan/djgo/djenv/lib/python3.6/site-packages']
Server time: Thu, 14 Nov 2019 10:21:49 +0900
#5. Change setting.py again
ALLOWED_HOSTS = ['127.0.0.1','.pythonanywhere.com']
- rerun django
(djenv) ivan@django:~/djgo$ python manage.py runserver 0.0.0.0:8000
Performing system checks...
System check identified no issues (0 silenced).
November 14, 2019 - 10:40:24
Django version 2.0.13, using settings 'mysite.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.
- Check using browser
django
View release notes for Django 2.0
The install worked successfully! Congratulations!
You are seeing this page because DEBUG=True is in your settings file and you have not configured any URLs.
3. Make Application
3-1. Make Appl
ivan@django:~/djgo$ source djenv/bin/activate
(djenv) ivan@django:~/djgo$ python manage.py startapp blog
(djenv) ivan@django:~/djgo$ ls -al
total 24
drwxrwxr-x 5 ivan ivan 4096 Nov 14 07:52 .
drwxr-xr-x 6 ivan ivan 4096 Nov 14 07:41 ..
drwxrwxr-x 3 ivan ivan 4096 Nov 14 07:52 blog
drwxrwxr-x 6 ivan ivan 4096 Nov 12 09:19 djenv
-rwxrwxr-x 1 ivan ivan 538 Nov 12 10:50 manage.py
drwxrwxr-x 3 ivan ivan 4096 Nov 14 01:42 mysite
(djenv) ivan@django:~/djgo$ ls -al blog
total 32
drwxrwxr-x 3 ivan ivan 4096 Nov 14 07:52 .
drwxrwxr-x 5 ivan ivan 4096 Nov 14 07:52 ..
-rw-rw-r-- 1 ivan ivan 63 Nov 14 07:52 admin.py
-rw-rw-r-- 1 ivan ivan 83 Nov 14 07:52 apps.py
-rw-rw-r-- 1 ivan ivan 0 Nov 14 07:52 __init__.py
drwxrwxr-x 2 ivan ivan 4096 Nov 14 07:52 migrations
-rw-rw-r-- 1 ivan ivan 57 Nov 14 07:52 models.py
-rw-rw-r-- 1 ivan ivan 60 Nov 14 07:52 tests.py
-rw-rw-r-- 1 ivan ivan 63 Nov 14 07:52 views.py
(djenv) ivan@django:~/djgo$
3-2. Let django to know about blog
(djenv) ivan@django:~/djgo$ vi mysite/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog', <<<<<<<<<<< Insert
]
3-3. Make model of blog
(djenv) ivan@django:~/djgo$ vi blog/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
3-4. Make table for model
- Migrate
(djenv) ivan@django:~/djgo$ python manage.py makemigrations blog
Migrations for 'blog':
blog/migrations/0001_initial.py
- Create model Post
(djenv) ivan@django:~/djgo$
- Apply model to database
(djenv) ivan@django:~/djgo$ python manage.py migrate blog
Operations to perform:
Apply all migrations: blog
Running migrations:
Applying blog.0001_initial... OK
(djenv) ivan@django:~/djgo$
- Check in DB
postgres=# \c myDB
You are now connected to database "myDB" as user "postgres".
myDB=#
myDB=# \d+
List of relations
Schema | Name | Type | Owner | Size | Description
--------+-----------------------------------+----------+--------+------------+-------------
public | auth_group | table | djuser | 0 bytes |
public | auth_group_id_seq | sequence | djuser | 8192 bytes |
public | auth_group_permissions | table | djuser | 0 bytes |
public | auth_group_permissions_id_seq | sequence | djuser | 8192 bytes |
public | auth_permission | table | djuser | 8192 bytes |
public | auth_permission_id_seq | sequence | djuser | 8192 bytes |
public | auth_user | table | djuser | 8192 bytes |
public | auth_user_groups | table | djuser | 0 bytes |
public | auth_user_groups_id_seq | sequence | djuser | 8192 bytes |
public | auth_user_id_seq | sequence | djuser | 8192 bytes |
public | auth_user_user_permissions | table | djuser | 0 bytes |
public | auth_user_user_permissions_id_seq | sequence | djuser | 8192 bytes |
public | blog_post | table | djuser | 8192 bytes |
public | blog_post_id_seq | sequence | djuser | 8192 bytes |
public | django_admin_log | table | djuser | 8192 bytes |
public | django_admin_log_id_seq | sequence | djuser | 8192 bytes |
public | django_content_type | table | djuser | 8192 bytes |
public | django_content_type_id_seq | sequence | djuser | 8192 bytes |
public | django_migrations | table | djuser | 16 kB |
public | django_migrations_id_seq | sequence | djuser | 8192 bytes |
public | django_session | table | djuser | 8192 bytes |
(21 rows)
myDB=#
myDB=# select * from blog_post;
id | title | text | created_date | published_date | author_id
----+-------+------+--------------+----------------+-----------
(0 rows)
4. URL & Views
4-1. For django admin
- Edit admin.py
(djenv) ivan@django:~/djgo$ vi blog/admin.py
from django.contrib import admin
from .models import Post
admin.site.register(Post)
- Runserver again
(djenv) ivan@django:~/djgo$ python manage.py runserver 0.0.0.0:8000
Performing system checks...
System check identified no issues (0 silenced).
November 15, 2019 - 16:49:50
Django version 2.0.13, using settings 'mysite.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.
- Create super user
(djenv) ivan@django:~/djgo$ python manage.py createsuperuser
Username (leave blank to use 'ivan'):
Email address: admin@mail.com
Password:
Password (again):
This password is too short. It must contain at least 8 characters.
Password:
Password (again):
Superuser created successfully.
(djenv) ivan@django:~/djgo$
- Check using browser
4-2. URL
- Edit urls.py
(djenv) ivan@django:~/djgo$ vi mysite/urls.py
"""mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')),
]
(djenv) ivan@django:~/djgo$
- Edit blog/urls.py
(djenv) ivan@django:~/djgo$ vi blog/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.post_list, name='post_list'),
]
4-3. Views
- make views
(djenv) ivan@django:~/djgo$ vi blog/views.py
(djenv) ivan@django:~/djgo$ more blog/views.py
from django.shortcuts import render
# Create your views here.
def post_list(request):
return render(request, 'blog/post_list.html', {})
(djenv) ivan@django:~/djgo$
- Check browser
TemplateDoesNotExist at /
blog/post_list.html
Request Method: GET
Request URL: http://192.168.56.200:8000/
Django Version: 2.0.13
Exception Type: TemplateDoesNotExist
Exception Value:
blog/post_list.html
Exception Location: /home/ivan/djgo/djenv/lib/python3.6/site-packages/django/template/loader.py in get_template, line 19
Python Executable: /home/ivan/djgo/djenv/bin/python
Python Version: 3.6.8
Python Path:
['/home/ivan/djgo',
'/usr/lib/python36.zip',
'/usr/lib/python3.6',
'/usr/lib/python3.6/lib-dynload',
'/home/ivan/djgo/djenv/lib/python3.6/site-packages']
Server time: Fri, 15 Nov 2019 17:22:39 +0900
4-4. Templetes
- Make directory
(djenv) ivan@django:~/djgo$ mkdir blog/templates
(djenv) ivan@django:~/djgo$ mkdir blog/templates/blog
(djenv) ivan@django:~/djgo$ touch blog/templates/blog/post_list.html
(djenv) ivan@django:~/djgo$
- restart runserver
(djenv) ivan@django:~/djgo$ python manage.py runserver 0.0.0.0:8000
Performing system checks...
System check identified no issues (0 silenced).
November 15, 2019 - 17:43:37
Django version 2.0.13, using settings 'mysite.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.
[15/Nov/2019 17:43:42] "GET / HTTP/1.1" 200 0
- Check browser
Blank displayed
- Edit post_list.html
(djenv) ivan@django:~/djgo$ vi blog/templates/blog/post_list.html
<html>
<p>Hi there!</p>
<p>It works!</p>
</html>
- Check browser
Hi there!
It works!
- Edit post_list.html again
(djenv) ivan@django:~/djgo$ vi blog/templates/blog/post_list.html
<html>
<head>
<title>Ivan's blog</title>
</head>
<body>
<p>Hi there!</p>
<p>It works!</p>
</body>
</html>
- Check browser
Displayed same with before
but title is changes
* Tag
<h1>A heading</h1> - 큰 제목
<h2>A sub-heading</h2> - 중 제목
<h3>A sub-sub-heading</h3> - 소 제목... <h6>레벨까지 사용할 수 있습니다.
<em>text</em> - 텍스트 기울기 (Italic)
<strong>text</strong> - 텍스트를 두껍게(Bold)
<br /> - 줄바꿈 (br은 스스로 닫히는 태그로 속성을 사용할 수 없습니다)
<a href="http://djangogirls.org">link</a> - 하이퍼링크 걸기
<ul><li>first item</li><li>second item</li></ul>- 목록 만들기
<div></div> - 페이지 섹션
- Change post_list.html again
(djenv) ivan@django:~/djgo$ vi blog/templates/blog/post_list.html
<html>
<head>
<title>Django Girls blog</title>
</head>
<body>
<div>
<h1><a href="">Django Girls Blog</a></h1>
</div>
<div>
<p>published: 14.06.2014, 12:14</p>
<h2><a href="">My first post</a></h2>
<p>Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum. Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus.</p>
</div>
<div>
<p>published: 14.06.2014, 12:14</p>
<h2><a href="">My second post</a></h2>
<p>Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum. Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut f.</p>
</div>
</body>
</html>
4-5. Django Shell
- Shell start
(djenv) ivan@django:~/djgo$ python manage.py shell
Python 3.6.8 (default, Oct 7 2019, 12:59:55)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> Post.objects.all()
Traceback (most recent call last):
File "", line 1, in
NameError: name 'Post' is not defined
>>>
- Import and check
>>> from blog.models import Post
>>> Post.objects.all()
<QuerySet []>
>>>
- Create posts
>>> from django.contrib.auth.models import User
>>> User.objects.all()
<QuerySet [<User: ivan>]>
>>> me = User.objects.get(username='ivan')
>>>
>>> Post.objects.create(author=me, title='Sample title', text='Test')
<Post: Sample title>
>>>
>>> Post.objects.all()
<QuerySet [<Post: Sample title>]>
>>>
- Filtering
>>> Post.objects.filter(author=me)
<QuerySet [<Post: Sample title>]>
>>>
>>> Post.objects.filter(title__contains='title')
[<Post: Sample title>, <Post: 4th title of post>]
>>>
>>> Post.objects.filter(title_contains='title')
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/ivan/djgo/djenv/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/ivan/djgo/djenv/lib/python3.6/site-packages/django/db/models/query.py", line 839, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/home/ivan/djgo/djenv/lib/python3.6/site-packages/django/db/models/query.py", line 857, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/home/ivan/djgo/djenv/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1253, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/home/ivan/djgo/djenv/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1277, in _add_q
split_subq=split_subq,
File "/home/ivan/djgo/djenv/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1153, in build_filter
lookups, parts, reffed_expression = self.solve_lookup_type(arg)
File "/home/ivan/djgo/djenv/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1015, in solve_lookup_type
_, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
File "/home/ivan/djgo/djenv/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1379, in names_to_path
"Choices are: %s" % (name, ", ".join(available)))
django.core.exceptions.FieldError: Cannot resolve keyword 'title_contains' into field. Choices are: author, author_id, created_date, id, published_date, text, title
>>>
>>> Post.objects.filter(title__contains='title')
<QuerySet [<Post: Sample title>]>
>>> from django.utils import timezone
>>> Post.objects.filter(published_date__lte=timezone.now())
<QuerySet []>
>>> post = Post.objects.get(title="Sample title")
>>> post.publish()
>>> Post.objects.filter(published_date__lte=timezone.now())
<QuerySet [<Post: Sample title>]>
>>>
>>> Post.objects.order_by('-created_date')
<QuerySet [<Post: Sample title>]>
>>>
>>> Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
<QuerySet [<Post: Sample title>]>
>>>
>>>
>>>
>>>
>>> exit()
(djenv) ivan@django:~/djgo$
4-6. Dynamic data templete
- edit views.py
(djenv) ivan@django:~/djgo$ more blog/views.py
from django.shortcuts import render
def post_list(request):
return render(request, 'blog/post_list.html', {})
(djenv) ivan@django:~/djgo$ vi blog/views.py
(djenv) ivan@django:~/djgo$ more blog/views.py
from django.shortcuts import render
from django.utils import timezone
from .models import Post
def post_list(request):
posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
return render(request, 'blog/post_list.html', {'posts': posts})
(djenv) ivan@django:~/djgo$
- Change post_list.html
(djenv) ivan@django:~/djgo$ more blog/templates/blog/post_list.html
<html>
<head>
<title>Django Girls blog</title>
</head>
<body>
<div>
<h1><a href="">Django Girls Blog</a></h1>
</div>
<div>
{{ posts }}
</div>
</body>
</html>
(djenv) ivan@django:~/djgo$
'Development (Python, Django, C..)' 카테고리의 다른 글
[Django] Tutorial 따라하기 - 4 (0) | 2019.11.27 |
---|---|
[Django] Tutorial 따라하기 - 3 (0) | 2019.11.23 |
[Django] Tutorial 따라하기 - 2 (0) | 2019.11.19 |
[Django] Tutorial 따라하기 - 1 (0) | 2019.11.19 |
[Python] File I/O (0) | 2019.04.27 |