pyramidでdeformを使ってみる

以前の記事でmongoengineの使い方が解ってきました。今度はdeformを使ってのフォームの作成を試してみました。
最終的にはpyramid-deformを利用したフォーム連携を目指しますが、まずはdeformを素で使ったシンプルなフォームを作成してからpyramid-deformを利用に進みます。

1. deformのインストール

pyramid-deformをインストールします。deform、colanderも一緒にインストールされます。

$ pip install pyramid-deform

2. schemaの作成

フォームの構造はスキーマと呼ばれるクラスで定義します。
今回の例ではnameという文字列型の項目とshoe_sizeという数値型の項目を定義してます。

$ vi myform/schema.py
import colander

class Person(colander.MappingSchema):
    name = colander.SchemaNode(colander.String())
    shoe_size = colander.SchemaNode(
        colander.Integer(),
        missing = 0,
    )

3. viewの作成

「/form」でアクセス可能なviewを用意します。

$ vi myform/__init__.py
from pyramid.config import Configurator

def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    config = Configurator(settings=settings)
    config.include('pyramid_jinja2')
    config.add_static_view('static', 'static', cache_max_age=3600)
    config.add_route('form_index', '/form')
    config.scan()

    return config.make_wsgi_app()

$ vi myform/views.py
from pyramid.view   import view_config
from deform import Form
from deform import ValidationFailure
from myform.schema import Person

class ProjectorViews(object):
    def __init__(self, request):
        self.request = request

    @view_config(route_name='form_index', renderer="templates/form.jinja2")
    def site_view(self):
        schema = Person()
        myform = Form(schema, buttons=('submit',))

        if 'submit' in self.request.POST:
            controls = self.request.POST.items()
            try:
                appstruct = myform.validate(controls)
            except ValidationFailure, e:
                return {'form':e.render(), 'values': False}

            values = {
                "name": appstruct['name'],
                "shoe_size": appstruct['shoe_size'],
                }
            return {"form": myform.render(), "values": values}

        return {"form": myform.render(), "values": None}

4. templateの作成

テンプレートではPOSTされたら、その値をフォームの下に表示してます。

$ vi myform/templates/form.jinja2
<html>
<head>
  <title>Projector</title>
</head>
<body>
<h2>Hello Form!</h2>
<div >{{ form| safe }}</div>
<p>Valid form values: {{values.name}} and {{values.shoe_size}}.</p>
</body>
</html>

5. 確認

サーバを起動してこんな画面が表示されたらまずはdeform理解の第一歩に成功です。

f:id:taka512:20130928194035p:plain