formをレンダリングしたときにinput要素を使わないようにする(django)

確認画面を作るときなどに使えるかも

class XForm(forms.Form):
    item = forms.ChoiceField(choices=[(i, i) for i in xrange(3)])
    data = forms.DateTimeField(required=False)

class ReadOnlyWidget(forms.Widget):
    def render(self, name, value, attrs=None):
        return unicode(value or u"")

class NullWidget(forms.Widget):
    def render(self, name, value, attrs=None):
        return u""

def read_only(form):
    for k, field in form.fields.items():
        if isinstance(field.widget, forms.HiddenInput):
            form.fields[k] = forms.Field(label=field.label, widget=NullWidget, required=False)
        else:
            form.fields[k] = forms.Field(label=field.label, widget=ReadOnlyWidget, required=False)

結果

form = XForm(dict(item=3, date="2011-01-01"))
print form
print "----"
read_only(form)
print form

## <tr><th><label for="id_item">Item:</label></th><td><input type="text" name="item" value="3" id="id_item" /></td></tr>
## <tr><th><label for="id_date">Date:</label></th><td><input type="text" name="date" value="2011-01-01" id="id_date" /></td></tr>
## ----
## <tr><th><label for="id_item">Item:</label></th><td>3</td></tr>
## <tr><th><label for="id_date">Date:</label></th><td>2011-01-01</td></tr>