Django newforms のドキュメントを読みながら自分なりのメモ [Python]
http://michilu.com/django/doc-ja/newforms/
forms.Form から派生させたクラスを作り、 forms.XxxxField クラスのメンバーを定義
from django import newforms as forms class ContactForm(forms.Form): subject = forms.CharField(max_length=100) message = forms.CharField() sender = forms.EmailField() cc_myself = forms.BooleanField()
コンストラクタに辞書っぽいデータを渡すと束縛(bound)フォームになる。
is_valid() でデータ検証に成功すると、正規化したデータが cleaned_data から取得できる
<<< data = {'subject': 'hello', ... 'message': 'Hi there', ... 'sender': 'foo@example.com', ... 'cc_myself': True} <<< f = ContactForm(data) <<< f.is_valid() True <<< f.cleaned_data {'cc_myself': True, 'message': u'Hi there', 'sender': u'foo@example.com', 'subject': u'hello'}
is_valid() でデータ検証に失敗すると errors にエラーメッセージが入る
newform を使ったビューの実装例
from django.shortcuts import render_to_response from django.http import HttpResponseRedirect from django import newforms as forms class ContactForm(forms.Form): subject = forms.CharField(max_length=100) message = forms.CharField() sender = forms.EmailField() cc_myself = forms.BooleanField() def contact(request): if request.POST: f = ContactForm(request.POST) if f.is_valid: # ... do something with f.cleaned_data return HttpResponseRedirect('/url/on/success/') else: f = ContactForm() return render_to_response('contact.html', {'form': f})
Form のインスタンスを print すると、HTML タグ付きで出力されるので、上記で使ってるテンプレート contact.html の一番簡単なのは↓のようになる
<form method="post" action=""> <table>{{ form }}<table> <input type="submit" /> <form>
form のところを form.as_table とすると、同じ意味(結果)だけどより明示的。
forms.as_ul とか forms.as_p とかすると違うフォーマットで出力できる
これ以上のところは、まだ僕には難しいのでまた今度考える。
だいたい、↓のようなことが書いてあるらしい
・アップロードされたファイルを取り扱う方法
・サブクラス化して同じようは forms.Form クラスを書かないようにする
・フォームフィールドの指定できるパラメーターやカスタマイズ
・(フォーム)ウィジェットのカスタマイズ
・モデルからフォームの作成 form_for_model()
・モデルのインスタンスからフォームの作成 form_for_instance()
コメント 0