from django import newforms as forms from django.conf import settings from django.newforms.forms import BoundField, pretty_name from django.newforms import widgets, fields from django.template import Context, loader from nidvid.utils import output_debug class TemplatedForm(forms.Form): def as_template(self): "Helper function for fieldsting fields data from form." bound_fields = [BoundField(self, field, name) for name, field in self.fields.items()] c = Context(dict(form = self, bound_fields = bound_fields)) # TODO: check for template ... if template does not exist # we could just get_template_from_string to some default # or we could pass in the template name ... whatever we want t = loader.get_template('newforms/form.html') return t.render(c) def as_custom(self): "Returns this form rendered as HTML <tr>s -- excluding the <table></table>." normal_row = u'<tr><td></td><td>%(errors)s</td></tr><tr><th style="text-align:right">%(label)s</th><td>%(field)s%(help_text)s</td></tr>' return self._html_output( normal_row, u'<tr><td colspan="2">%s</td></tr>', '</td></tr>', u'<br />%s', False) def as_readonly_table(self): output = ['<table class="readonly_forms_table">'] for name, field in self.fields.items(): data = "" label = "" if not self.is_bound: data = self.initial.get(name, field.initial) if callable(data): data = data() else: # TODO see BoundField in django trunk data = field.widget.value_from_datadict(self.data, self.files, name) # Finally try one more methed to get the data if not data and hasattr(self, 'cleaned_data'): data = self.cleaned_data[name] if field.label is None: label = pretty_name(name) else: label = field.label label = label.strip(':') data = data or "" output.append('<tr><th>%s:</th><td>%s</td></tr>' % (label, data)) output.append('</table>') return u'\n'.join(output) def __str__(self): return self.as_template()