Django1.5でGoogle App Engineのチュートリアルをやったときのメモ

Google App Engine上のDjangoでのチュートリアル「Using Django with Appengine」邦訳 - WebOS Goodiesをやろうとしたところ、チュートリアルで使われているDjangoとGAEのバージョンが古くそのままでは動きませんでした。

色々なサイトを参考にしながら動くところまでこぎつけたので、そのメモです。
※どのディレクトリのファイルか分かりづらかったのでパスも書きました。
参考サイト
GAE - GoogleAppEngine/PythonでDjangoを使う方法 - Qiita
まず、GAEに付属しているDjango1.5のあるディレクトリにパスを通します。

$ vim ~/.bash_profile

PYTHONPATH = "/usr/local/google_appengine/lib/django-1.5:$PYTHONPATH"
export PYTHONPATH

Creating a project
ホームディレクトリにGAEというフォルダを作成し、プロジェクトを開始します。

$ cd ~
$ mkdir GAE
$ cd GAE
$ /usr/local/google_appengine/lib/django-1.5/django/bin/django-admin.py startproject appproject

これで、~/GAE以下にappprojectという名前のディレクトリが作成されます。チュートリアルにある、main.pyを作成する必要はありませんが、代わりに~/GAE/appproject/にappengine_config.pyを作成します。

$ cd appproject
$ vim appengine_config.py

# -*- coding: utf-8 -*-
import os
import sys

if os.environ.get('SERVER_SOFTWARE','').startswith('Dev'):
    sys.path.append('/Users/あなたのユーザ名/GAE/appproject/appproject')

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "appproject.settings")

つづいて、~/GAE/appproject/にapp.yamlを作成します。

application: appproject
version: 1
runtime: python27
api_version: 1
threadsafe: yes

libraries:
- name: django
  version: "1.5"

builtins:
- django_wsgi: on

続いて、チュートリアルにしたがって、以下のコマンドを打ちます。

$ python manage.py startapp poll

Editing the settings.py file
ここでは、~/GAE/appproject/appproject/settings.pyを編集していきます。

110 import os
111 ROOT_PATH = os.path.dirname(__file__)
112 
113 TEMPLATE_DIRS = (
114     # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
115     # Always use forward slashes, even on Windows.
116     # Don't forget to use absolute paths, not relative paths.
117     ROOT_PATH + '/templates',
118 )
119
120 INSTALLED_APPS = (
121     'django.contrib.auth',
122     'django.contrib.contenttypes',
123     'django.contrib.sessions',
124     'django.contrib.sites',
125     'django.contrib.messages',
126     'django.contrib.staticfiles',
127     # Uncomment the next line to enable the admin:
128     # 'django.contrib.admin',
129     # Uncomment the next line to enable admin documentation:
130     # 'django.contrib.admindocs',
131     'poll',
132 )

Write the URL configuration file
~/GAE/appproject/appproject/urls.pyを編集します。

 7 urlpatterns = patterns('',
  8     # Examples:
  9     # url(r'^$', 'appproject.views.home', name='home'),
 10     # url(r'^appproject/', include('appproject.foo.urls')),
 11 
 12     # Uncomment the admin/doc line below to enable admin documentation:
 13     # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
 14 
 15     # Uncomment the next line to enable the admin:
 16     # url(r'^admin/', include(admin.site.urls)),
 17     (r'^$', 'poll.views.index'),
 18     (r'^create/$', 'poll.views.create'),
 19     (r'^poll/(?P<poll_key>[^\.^/]+)/$', 'poll.views.poll_detail'),
 20     (r'^poll/(?P<poll_key>[^\.^/]+)/results/$', 'poll.views.poll_results'),

Write the models.py file.
~/GAE/appproject/poll/models.pyはそのままで動きました。
Writing the forms
~/GAE/appproject/poll/bforms.pyを作成します。

from django import newforms as forms

とありますが、newformsはformsに統一されたようなので、

from django import forms

で問題ありません。
また、crean_dataをcreaned_dataに変更します。

    def save(self):
        choice = models.Choice(poll = self.poll, choice = self.cleaned_data['choice'])
        choice.put()

Write the view
~/GAE/appproject/poll/views.pyを編集します。
モジュールのインポートが少し違います。CSRFはフォーム送信関係のセキュリティ対策のようです。

  1 from django.http import HttpResponse, HttpResponseRedirect
  2 import models
  3 import bforms
  4 from django.shortcuts import render_to_response
  5 from django.core.context_processors import csrf
 
 35     payload = dict(pollform=pollform, choiceforms=choiceforms)
 36     payload.update(csrf(request))
 37     return render('create.html', payload)

Writing the templates
~/GAE/appproject/poll/に、templatesディレクトリを作成し、そこにテンプレートファイル(.html)を作成していきます。チュートリアルではファイル名が分かりづらいですが、一個目のコードがindex.html、二個目のコードがbase.htmlです。
create.htmlに先ほどのCSRF関係のコードを書き足します。

{% extends 'base.html' %}

{% block contents %}
<form action="." method="post">
{% csrf_token %}
{{pollform.as_p}}

{% for form in choiceforms %}
{{form.as_p}}
{% endfor %}

<input type="submit" name="createpoll" value="createpoll" />

</form>

{% endblock %}

これで、サーバーを立ち上げ、http://localhost:8080にアクセスすれば動いている(はず)です。

$ cd ~/GAE/appproject
$ dev_appserver.py .

それで、Applications OverviewでCreate Applicationして、

$ cd ~/GAE/appproject
$ appcfg.py --oauth2 -A プロジェクト名 update プロジェクトのディレクトリ

とやればデプロイされ、http://プロジェクト名.appspot.comでアクセスできるらしいです(このプロジェクト名だともう使われているだろうけど…)。

ただ、このチュートリアルのコードだとどうがんばっても投票数が増えていかないと思うんですが、どうなんだろう…。