갈루아의 반서재

Step 1 — Installing Django

사용자의 필요와 개발환경에 따라 Django 를 설치하는 데에는 여러가지 방법이 있지만, 여기서는 Django 공식 홈페이지의 Install an official release에 따라 설치해보기로 한다. 

먼저 pip를 설치한다. standalone pip installer를 사용하여 설치하거나, 이미 pip 가 설치되어 있다면 최신 버전으로 업데이트한다. 현재 20.1.1 버전이 설치되어 있으며, 아나콘다 환경 기준 최신 버전임을 알 수 있다.

(quintic) fossa@fossa:~$ pip --version
pip 20.1.1 from /home/fossa/anaconda3/envs/quintic/lib/python3.8/site-packages/pip (python 3.8)
(quintic) fossa@fossa:~$ python -m pip install --upgrade pip
Requirement already up-to-date: pip in ./anaconda3/envs/quintic/lib/python3.8/site-packages (20.1.1)

프로젝트별로 관리가 가능하도록 Anaconda 또는 venv 등의 툴을 사용하여 가상환경을 생성한다. 해당 환경을 활성화한 후 Django 설치를 시작한다. 여기서는 Anaconda 를 통해 생성된 가상환경을 통해 나머지 과정을 진행한다. 다음 명령어를 통해 Django 를 설치한다. 

(quintic) fossa@fossa:~$ python -m pip install Django
Collecting Django
  Downloading Django-3.0.8-py3-none-any.whl (7.5 MB)
     |████████████████████████████████| 7.5 MB 3.0 MB/s
Collecting sqlparse>=0.2.2
  Downloading sqlparse-0.3.1-py2.py3-none-any.whl (40 kB)
     |████████████████████████████████| 40 kB 8.1 MB/s
Collecting asgiref~=3.2
  Downloading asgiref-3.2.10-py3-none-any.whl (19 kB)
Collecting pytz
  Downloading pytz-2020.1-py2.py3-none-any.whl (510 kB)
     |████████████████████████████████| 510 kB 38.7 MB/s
Installing collected packages: sqlparse, asgiref, pytz, Django
Successfully installed Django-3.0.8 asgiref-3.2.10 pytz-2020.1 sqlparse-0.3.1

설치된 Django 버전은 3.0.8 이다.

(quintic) fossa@fossa:~$ django-admin --version
3.0.8

 

Step 2 — Adjusting Firewall Settings

필요하다면 각자의 환경에 맞게 방화벽 설정한다. 구글클라우드 플랫폼을 사용하고 있다면, VPC 네트워크 > 방화벽 메뉴에서 다음과 같이 추가하면 된다.

 

Step 3 — Starting the Project

관리자 태스크를 수행하는 django-admin 유틸리티에 프로젝트 디렉토리를 생성하는 startproject 명령을 덧붙여 코드가 저장되기를 원하는 디렉토리로 이동하여 다음 명령을 실행한다. 

(quintic) fossa@fossa:~$ django-admin startproject treadstone

startproject 는 현재 디렉토리 또는 주어진 목적지에 프로젝트 이름을 가진 Django 프로젝트 디렉토리 구조를 만들어준다. 기본적으로 해당 디렉토리에는 manage.py 파일과 settings.py 등의 파일을 가진 프로젝트 패키지가 생성된다.

treadstone/
    manage.py
    treadstone/
        __init__.py
        settings.py
        urls.py
        asgi.py
        wsgi.py

manage.py 파일은 프로젝트 패키지를 sys.path 에 두도록 하며, DJANGO_SETTINGS_MODULE 환경변수가 프로젝트의 settings.py 파일을 가르키도록 하는 기능을 한다. 

#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys


def main():
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'treadstone.settings')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)


if __name__ == '__main__':
    main()

 

Step 4 — Configuring Django

서버를 실행시키고 웹사이트를 보기 위해서는 /home/fossa/treadstone/treadstone/settings.py 파일을 열어 ALLOWED_HOSTS 항목에 여러분의 ip 를 리스트 형식으로 등록시킨다.

ALLOWED_HOSTS = ['**.***.*.***']

Django docs에 따르면, ALLOWED_HOSTS 변수에는 호스트/도메인 이름을 나타내는 문자열 리스트가 포함된다. 

 

Step 5 — Accessing the Django Web App

설정이 끝나면 다시 manage.py 파일이 위치한 /home/fossa/treadstone/ 로 돌아와 다음과 같이 웹서버를 구동한다. 앞선 4단계에서 ALLOWED_HOSTS 에 ip 정보를 입력하지 않은 경우 다음과 같이 추가하라는 메시지를 보게 된다. 

(quintic) fossa@fossa:~/treadstone$ python manage.py runserver 0.0.0.0:8000
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).

You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): ad                           min, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.

July 18, 2020 - 09:38:32
Django version 3.0.8, using settings 'treadstone.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.
Invalid HTTP_HOST header: '**.***.*.***:8000'. You may need to add '**.***.*.***' to ALLOWED_HOSTS.
Bad Request: /

리스트에 ip 를 추가한 후 다시 웹서버를 구동해보자. 마이그레이션이 필요하다는 메시지가 뜬다. 

(quintic) fossa@fossa:~/treadstone$ python manage.py runserver 0.0.0.0:8000
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).

You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.

July 18, 2020 - 09:45:19
Django version 3.0.8, using settings 'treadstone.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.
[18/Jul/2020 09:45:31] "GET / HTTP/1.1" 200 16351

다음과 같이 마이그레이션을 진행한 후 다시 웹서버를 구동한다.

(quintic) fossa@fossa:~/treadstone$ 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 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 sessions.0001_initial... OK
(quintic) fossa@fossa:~/treadstone$ python manage.py runserver 0.0.0.0:8000
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
July 18, 2020 - 09:46:54
Django version 3.0.8, using settings 'treadstone.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.

웹브라우저 주소창에 여러분의 실제 IP 를 다음과 같이 입력하면 기본 Django 홈페이지를 볼 수 있다.

http://**.***.*.**:8000/

관리자를 생성한 후 관리자 페이지 로그인을 해보자. 다음과 같이 정보를 입력하여 관리자 계정을 생성한다. 

(quintic) fossa@fossa:~/treadstone$ python manage.py createsuperuser
Username (leave blank to use 'fossa'):
Email address:
Password:
Password (again):
Superuser created successfully.
(quintic) fossa@fossa:~/treadstone$

http://**.***.*.**:8000/admin 으로 이동하면 다음과 같은 로그인 창을 볼 수 있다. 

앞서 만든 계정으로 로그인해보자. 

Users 를 클릭해보면 앞서 만든 관리자 계정이 존재함을 알 수 있다.