Google App Engine用フレームワークKayで、Formの初期値を設定する

Google App Engine用フレームワークKayで、Formの初期値を設定する」より。

Google App EngineフレームワークKayで、Formの初期値を設定するには、コンストラクタに初期値を辞書 (dictionary) で渡します。

from kay.utils import forms
class MyForm(forms.Form):
message = forms.TextField(required=True)
flags = forms.MultiChoiceField(choices=[1, 2, 3])

def index(request):
form = MyForm({'message':u'メッセージ', 'flags': [1,3]}) #フォームに初期値を設定
return render_to_response('myapp/index.html',
{'form':form.as_widget()})

ModelFormにmodelの値を設定するには、キーワード引数instanceを使用します。

from google.appengine.ext import db
from kay.utils.forms.modelform import ModelForm

class MyModel(db.Model):
message = db.StringProperty()

class MyForm(ModelForm):
class Meta:
model = MyModel

def index(request):
model = MyModel(message=u'メッセージ') #モデルに初期値を設定
form = MyForm(instance=model) #フォームにモデルの値を設定
return render_to_response('myapp/index.html',
{'form':form.as_widget()})

MultiChoiceFieldの初期値を設定するには、「ModelFormのMultiChoiceFieldの初期値について」のStringListPropertyPassThroughを使用する必要があります。

from google.appengine.ext import db
from kay.utils.forms.modelform import ModelForm

class StringListPropertyPassThrough(db.StringListProperty):
def get_value_for_form(self, instance):
value = db.ListProperty.get_value_for_form(self, instance)
if not value:
return None
return value

def make_value_from_form(self, value):
if not value:
return []
return value

class MyModel(db.Model):
flags = StringListPropertyPassThrough()

class MyForm(ModelForm):
flags = forms.MultiChoiceField(choices=[u'Python', 'Perl', 'PHP'])
class Meta:
model = MyModel

def index(request):
model = MyModel(flags = [u'Python', 'PHP'])
form = MyForm(instance=model)
return render_to_response('myapp/index.html',
{'form':form.as_widget()})