Return to Tech/python
Return to Tech/python

Python - django

Djangoについて

ModelViewController系のWebアプリケーションフレームワークです。

pipを用いて django をインストールします。
(.venv) $ pip3 install django
Collecting django
  Downloading Django-1.8.5-py2.py3-none-any.whl (6.2MB)
    100% |????????????????????????????????| 6.2MB 8.8kB/s
Installing collected packages: django
Successfully installed django-1.8.5


(.venv) $ pip3 freeze
Django==1.8.5
requests==2.8.1


Djangoプロジェクトを作成します。
$ /opt/python3.5.0/bin/django-admin startproject test01


test01ディレクトリが作成されます。構成は下記の通り。
test01
  +File - manage.py
  +Directory - test01
  +File - __init__.py
  +File - settings.py
  +File - urls.py
  +File - wsgi.py

test01プロジェクトにDjangoアプリケーションを作成します。
$ cd test01
$ /opt/python3.5.0/bin/python3 manage.py startapp app01


app01ディレクトリが作成されます。構成は下記の通り。
test01
  +File - manage.py
  +Directory - test01
  +File - __init__.py
  +File - settings.py    # アプリケーション定義ファイル
  +File - urls.py
  +File - wsgi.py
  +Directory - app01
  +File - admin.py
  +File - __init__.py
  +File - models.py
  +File - tests.py
  +File - views.py
  +Directory - migrations
    +File - __init__.py


アプリケーション定義
test01/settings.pyのINSTALLED_APPS定義に app01を追加します。

File:/python_projects/test01/settings.py
# Application definition
INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app01',
)


モデルを調整します。

File:/python_projects/test01/app01/models.py
from django.db import models

# Create your models here.
class Memo(models.Model):
    memo_text = models.CharField(max_length=500)

モデル調整用マイグレーションファイルを作成します。
$ /opt/python3.5.0/bin/python3 manage.py makemigrations app01
Migrations for 'app01':
  0001_initial.py:
    - Create model Memo


マイグレーション
$ /opt/python3.5.0/bin/python3 manage.py migrate
Operation to perform:
  Synchronize unmigrated apps: staticfiles, messages
  Apply all migrations: contenttypes, auth, admin, app01, sessions
Synchronizing apps without migrations:
  Creating tables...
    Running deferred SQL...
  Installing custom SQL...
Running migrations:
  Rendering model states... DONE
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying app01.0001_initial... 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 sessions.0001_initial... OK


この時点でdjangoのデフォルトページが表示されるか確認します。
下記のようにdjang自前のウェブサーバを起動します。
$ /opt/python3.5.0/bin/python3 manage runserver IPアドレス:ポート番号

Webブラウザで http://IPアドレス:ポート番号/ を開き、表示されることを確認しま>す。


Return to Tech/python
Return to Tech/python