DjangoとPostgreSQLでWebアプリを作成する流れ
前の記事でDjangoをインストールしました。せっかくなので、簡単なアプリを作成しながら、Djangoの開発の流れをみていきます。Djangoの特徴として、簡単に素早くアプリを作成できるというものがありますので、これを体験してみました。
以下記事を参考にしてみると、コマンドラインからアプリのフォルダ構成を作成したり、DBのスキーマを作成したり、モデルの構成にエラーがないか調べるなどをすることができます。
http://django-docs-ja.readthedocs.org/en/latest/intro/tutorial01.html
これらを検証するために実際にやってみました。
DBはPostgreSQLを使ってみます。
PostgreSQLのインストール
$ sudo apt-get install postgresql-9.1 [ ok ] Starting PostgreSQL 9.1 database server: main. Setting up xml-core (0.13+nmu2) ... Processing triggers for sgml-base ... # su postgres $ psql postgres psql (9.1.16) Type "help" for help. postgres=# create database test; CREATE DATABASE postgres=# \q
PostgreSQLの拡張モジュールもインストールします
$ sudo apt-get install python-psycopg2
DBの設定
プロジェクトフォルダ直下のsetting.pyに書きます(myapp/settings.py)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'test', # Or path to database file if using sqlite3.
'USER': 'postgres', # Not used with sqlite3.
'PASSWORD': 'postgres', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
テーブルの作成
settings.pyにはあらかじめ以下のアプリ設定がされています。
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
# 'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
これらを有効にするため、テーブルを作成してみます。
postgresユーザで以下のコマンドを打ちます。
$ python manage.py syncdb
テーブルが作成されました。
アプリケーションの作成
pollsというアプリのフォルダ構造を作成するために以下のコマンドを打ちます。
$ python manage.py startapp polls
以下のフォルダとファイルが作成されます。
- manage.py
- polls
- __init__.py
- models.py
- tests.py
- views.py
モデルの作成
models.pyに以下を追加します。
from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
settings.pyのINSTALLED_APPSにpollsを追加します。
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
# 'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'polls'
)
以下のコマンドを打つとmodels.pyに追加したスキーマ定義が反映されます。
$ python manage.py sql polls
BEGIN;
CREATE TABLE "polls_poll" (
"id" serial NOT NULL PRIMARY KEY,
"question" varchar(200) NOT NULL,
"pub_date" timestamp with time zone NOT NULL
)
;
CREATE TABLE "polls_choice" (
"id" serial NOT NULL PRIMARY KEY,
"poll_id" integer NOT NULL REFERENCES "polls_poll" ("id") DEFERRABLE INITIALLY DEFERRED,
"choice" varchar(200) NOT NULL,
"votes" integer NOT NULL
)
;
COMMIT;
ビューの作成
URLスキームの作成のために、urls.pyを以下のように編集します。urls.pyはROOT_URLCONF = 'myapp.urls'でインポートされています。
urlpatterns = patterns('',
url(r'^polls/$', 'polls.views.index'),
url(r'^polls/(?P\d+)/$', 'polls.views.detail'),
url(r'^polls/(?P\d+)/results/$', 'polls.views.results'),
url(r'^polls/(?P\d+)/vote/$', 'polls.views.vote'),
)
実際にview.pyを編集してビューを作成してみます。
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You're at the poll index.")
def detail(request, poll_id):
return HttpResponse("You're looking at poll %s." % poll_id)
def results(request, poll_id):
return HttpResponse("You're looking at the results of poll %s." % poll_id)
def vote(request, poll_id):
return HttpResponse("You're voting on poll %s." % poll_id)
サーバを起動してブラウザからhttp://192.168.33.10:8000/polls/34/にアクセスしてみると、You're looking at poll 34.と表示されました。
今回はDjangoを使ったアプリ作成の流れを見ていきました。次回はDBの登録、検索などをやってみます。

- 作者: 株式会社ビープラウド
- 出版社/メーカー: 秀和システム
- 発売日: 2015/05/21
- メディア: Kindle版
- この商品を含むブログを見る