djangoを使ってみる(2) PostgreSQL編
引き続いて、下記サイトを参考にしてPostgreSQLでも動作確認
【Python】 Djangoをapt-getでUbuntuにインストール
http://blog.srengine.com/2008/03/python-djangoapt-getubuntu.html
PostgreSQLをインストールした状態で、djangoの設定を2点だけ変更する。
psycopg2のインストール
$ sudo apt-get install python-psycopg2
myprj/setting.pyでDB設定を以下のように変更する。HOST,PORTなどは適当に。
DATABASES = { 'default': { 'ENGINE': 'postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'myprj', # Or path to database file if using sqlite3. 'USER': 'postgres', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '127.0.0.1', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '5432', # Set to empty string for default. Not used with sqlite3. } } TIME_ZONE = 'Asia/Tokyo'
この状態で、syncdbするとOK。
$ sudo python manage.py syncdb
以降は、試験的に動作させる例。
DBに書き込み(test data)
$ sudo python manage.py shell >>> from myapp.models import * >>> User(username='foo', password='brabra', description='Hello', score=0).save() >>> User(username='hoge', password='brabra', description='Good-bye', score=0).save() >>> us = User.objects.all() >>> for u in us: ... print u.username, u.password, u.datetime ... foo brabra 2012-05-09 19:39:29.085185 hoge brabra 2012-05-09 19:39:37.485181
/var/www/myprj/myapp/views.pyの設定(test data用)
# Create your views here. from django.shortcuts import render_to_response, get_object_or_404 import models def index(request): users = models.User.objects.all() return render_to_response('index.html', { 'users': users })
$ sudo mkdir myapp/template $ sudo emacs -nw myapp/template/index.html
index.htmlの中身
<html> <body> {% for user in users %} <p>{{user.username}}, {{user.password}}, {{user.description}}</p> {% endfor %} </body> </html>
$ sudo emacs -nw urls.py
urls.pyの中身
from django.conf.urls.defaults import * # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^myprj/', include('myprj.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: # (r'^admin/', include(admin.site.urls)), (r'^myprj/myapp/$', 'myprj.myapp.views.index'), )
apacheのrestart
$ sudo service apache2 restart
http://localhost/myprj/myapp にアクセスする。