PageRenderTime 45ms CodeModel.GetById 12ms RepoModel.GetById 1ms app.codeStats 0ms

/tests/regressiontests/forms/tests/forms.py

https://code.google.com/p/mango-py/
Python | 1724 lines | 1683 code | 16 blank | 25 comment | 12 complexity | 17beefea3cf04a0dedfb41b9e743e8a2 MD5 | raw file
Possible License(s): BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

  1. # -*- coding: utf-8 -*-
  2. import datetime
  3. from decimal import Decimal
  4. import re
  5. import time
  6. from django.core.files.uploadedfile import SimpleUploadedFile
  7. from django.forms import *
  8. from django.http import QueryDict
  9. from django.template import Template, Context
  10. from django.utils.datastructures import MultiValueDict, MergeDict
  11. from django.utils.safestring import mark_safe
  12. from django.utils.unittest import TestCase
  13. class Person(Form):
  14. first_name = CharField()
  15. last_name = CharField()
  16. birthday = DateField()
  17. class PersonNew(Form):
  18. first_name = CharField(widget=TextInput(attrs={'id': 'first_name_id'}))
  19. last_name = CharField()
  20. birthday = DateField()
  21. class FormsTestCase(TestCase):
  22. # A Form is a collection of Fields. It knows how to validate a set of data and it
  23. # knows how to render itself in a couple of default ways (e.g., an HTML table).
  24. # You can pass it data in __init__(), as a dictionary.
  25. def test_form(self):
  26. # Pass a dictionary to a Form's __init__().
  27. p = Person({'first_name': u'John', 'last_name': u'Lennon', 'birthday': u'1940-10-9'})
  28. self.assertTrue(p.is_bound)
  29. self.assertEqual(p.errors, {})
  30. self.assertTrue(p.is_valid())
  31. self.assertEqual(p.errors.as_ul(), u'')
  32. self.assertEqual(p.errors.as_text(), u'')
  33. self.assertEqual(p.cleaned_data["first_name"], u'John')
  34. self.assertEqual(p.cleaned_data["last_name"], u'Lennon')
  35. self.assertEqual(p.cleaned_data["birthday"], datetime.date(1940, 10, 9))
  36. self.assertEqual(str(p['first_name']), '<input type="text" name="first_name" value="John" id="id_first_name" />')
  37. self.assertEqual(str(p['last_name']), '<input type="text" name="last_name" value="Lennon" id="id_last_name" />')
  38. self.assertEqual(str(p['birthday']), '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" />')
  39. try:
  40. p['nonexistentfield']
  41. self.fail('Attempts to access non-existent fields should fail.')
  42. except KeyError:
  43. pass
  44. form_output = []
  45. for boundfield in p:
  46. form_output.append(str(boundfield))
  47. self.assertEqual('\n'.join(form_output), """<input type="text" name="first_name" value="John" id="id_first_name" />
  48. <input type="text" name="last_name" value="Lennon" id="id_last_name" />
  49. <input type="text" name="birthday" value="1940-10-9" id="id_birthday" />""")
  50. form_output = []
  51. for boundfield in p:
  52. form_output.append([boundfield.label, boundfield.data])
  53. self.assertEqual(form_output, [
  54. ['First name', u'John'],
  55. ['Last name', u'Lennon'],
  56. ['Birthday', u'1940-10-9']
  57. ])
  58. self.assertEqual(str(p), """<tr><th><label for="id_first_name">First name:</label></th><td><input type="text" name="first_name" value="John" id="id_first_name" /></td></tr>
  59. <tr><th><label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" value="Lennon" id="id_last_name" /></td></tr>
  60. <tr><th><label for="id_birthday">Birthday:</label></th><td><input type="text" name="birthday" value="1940-10-9" id="id_birthday" /></td></tr>""")
  61. def test_empty_dict(self):
  62. # Empty dictionaries are valid, too.
  63. p = Person({})
  64. self.assertTrue(p.is_bound)
  65. self.assertEqual(p.errors['first_name'], [u'This field is required.'])
  66. self.assertEqual(p.errors['last_name'], [u'This field is required.'])
  67. self.assertEqual(p.errors['birthday'], [u'This field is required.'])
  68. self.assertFalse(p.is_valid())
  69. try:
  70. p.cleaned_data
  71. self.fail('Attempts to access cleaned_data when validation fails should fail.')
  72. except AttributeError:
  73. pass
  74. self.assertEqual(str(p), """<tr><th><label for="id_first_name">First name:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="first_name" id="id_first_name" /></td></tr>
  75. <tr><th><label for="id_last_name">Last name:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="last_name" id="id_last_name" /></td></tr>
  76. <tr><th><label for="id_birthday">Birthday:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="birthday" id="id_birthday" /></td></tr>""")
  77. self.assertEqual(p.as_table(), """<tr><th><label for="id_first_name">First name:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="first_name" id="id_first_name" /></td></tr>
  78. <tr><th><label for="id_last_name">Last name:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="last_name" id="id_last_name" /></td></tr>
  79. <tr><th><label for="id_birthday">Birthday:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="birthday" id="id_birthday" /></td></tr>""")
  80. self.assertEqual(p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" /></li>
  81. <li><ul class="errorlist"><li>This field is required.</li></ul><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></li>
  82. <li><ul class="errorlist"><li>This field is required.</li></ul><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /></li>""")
  83. self.assertEqual(p.as_p(), """<ul class="errorlist"><li>This field is required.</li></ul>
  84. <p><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" /></p>
  85. <ul class="errorlist"><li>This field is required.</li></ul>
  86. <p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></p>
  87. <ul class="errorlist"><li>This field is required.</li></ul>
  88. <p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /></p>""")
  89. def test_unbound_form(self):
  90. # If you don't pass any values to the Form's __init__(), or if you pass None,
  91. # the Form will be considered unbound and won't do any validation. Form.errors
  92. # will be an empty dictionary *but* Form.is_valid() will return False.
  93. p = Person()
  94. self.assertFalse(p.is_bound)
  95. self.assertEqual(p.errors, {})
  96. self.assertFalse(p.is_valid())
  97. try:
  98. p.cleaned_data
  99. self.fail('Attempts to access cleaned_data when validation fails should fail.')
  100. except AttributeError:
  101. pass
  102. self.assertEqual(str(p), """<tr><th><label for="id_first_name">First name:</label></th><td><input type="text" name="first_name" id="id_first_name" /></td></tr>
  103. <tr><th><label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" id="id_last_name" /></td></tr>
  104. <tr><th><label for="id_birthday">Birthday:</label></th><td><input type="text" name="birthday" id="id_birthday" /></td></tr>""")
  105. self.assertEqual(p.as_table(), """<tr><th><label for="id_first_name">First name:</label></th><td><input type="text" name="first_name" id="id_first_name" /></td></tr>
  106. <tr><th><label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" id="id_last_name" /></td></tr>
  107. <tr><th><label for="id_birthday">Birthday:</label></th><td><input type="text" name="birthday" id="id_birthday" /></td></tr>""")
  108. self.assertEqual(p.as_ul(), """<li><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" /></li>
  109. <li><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></li>
  110. <li><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /></li>""")
  111. self.assertEqual(p.as_p(), """<p><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" /></p>
  112. <p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></p>
  113. <p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /></p>""")
  114. def test_unicode_values(self):
  115. # Unicode values are handled properly.
  116. p = Person({'first_name': u'John', 'last_name': u'\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111', 'birthday': '1940-10-9'})
  117. self.assertEqual(p.as_table(), u'<tr><th><label for="id_first_name">First name:</label></th><td><input type="text" name="first_name" value="John" id="id_first_name" /></td></tr>\n<tr><th><label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" id="id_last_name" /></td></tr>\n<tr><th><label for="id_birthday">Birthday:</label></th><td><input type="text" name="birthday" value="1940-10-9" id="id_birthday" /></td></tr>')
  118. self.assertEqual(p.as_ul(), u'<li><label for="id_first_name">First name:</label> <input type="text" name="first_name" value="John" id="id_first_name" /></li>\n<li><label for="id_last_name">Last name:</label> <input type="text" name="last_name" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" id="id_last_name" /></li>\n<li><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" value="1940-10-9" id="id_birthday" /></li>')
  119. self.assertEqual(p.as_p(), u'<p><label for="id_first_name">First name:</label> <input type="text" name="first_name" value="John" id="id_first_name" /></p>\n<p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" id="id_last_name" /></p>\n<p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" value="1940-10-9" id="id_birthday" /></p>')
  120. p = Person({'last_name': u'Lennon'})
  121. self.assertEqual(p.errors['first_name'], [u'This field is required.'])
  122. self.assertEqual(p.errors['birthday'], [u'This field is required.'])
  123. self.assertFalse(p.is_valid())
  124. self.assertEqual(p.errors.as_ul(), u'<ul class="errorlist"><li>first_name<ul class="errorlist"><li>This field is required.</li></ul></li><li>birthday<ul class="errorlist"><li>This field is required.</li></ul></li></ul>')
  125. self.assertEqual(p.errors.as_text(), """* first_name
  126. * This field is required.
  127. * birthday
  128. * This field is required.""")
  129. try:
  130. p.cleaned_data
  131. self.fail('Attempts to access cleaned_data when validation fails should fail.')
  132. except AttributeError:
  133. pass
  134. self.assertEqual(p['first_name'].errors, [u'This field is required.'])
  135. self.assertEqual(p['first_name'].errors.as_ul(), u'<ul class="errorlist"><li>This field is required.</li></ul>')
  136. self.assertEqual(p['first_name'].errors.as_text(), u'* This field is required.')
  137. p = Person()
  138. self.assertEqual(str(p['first_name']), '<input type="text" name="first_name" id="id_first_name" />')
  139. self.assertEqual(str(p['last_name']), '<input type="text" name="last_name" id="id_last_name" />')
  140. self.assertEqual(str(p['birthday']), '<input type="text" name="birthday" id="id_birthday" />')
  141. def test_cleaned_data_only_fields(self):
  142. # cleaned_data will always *only* contain a key for fields defined in the
  143. # Form, even if you pass extra data when you define the Form. In this
  144. # example, we pass a bunch of extra fields to the form constructor,
  145. # but cleaned_data contains only the form's fields.
  146. data = {'first_name': u'John', 'last_name': u'Lennon', 'birthday': u'1940-10-9', 'extra1': 'hello', 'extra2': 'hello'}
  147. p = Person(data)
  148. self.assertTrue(p.is_valid())
  149. self.assertEqual(p.cleaned_data['first_name'], u'John')
  150. self.assertEqual(p.cleaned_data['last_name'], u'Lennon')
  151. self.assertEqual(p.cleaned_data['birthday'], datetime.date(1940, 10, 9))
  152. def test_optional_data(self):
  153. # cleaned_data will include a key and value for *all* fields defined in the Form,
  154. # even if the Form's data didn't include a value for fields that are not
  155. # required. In this example, the data dictionary doesn't include a value for the
  156. # "nick_name" field, but cleaned_data includes it. For CharFields, it's set to the
  157. # empty string.
  158. class OptionalPersonForm(Form):
  159. first_name = CharField()
  160. last_name = CharField()
  161. nick_name = CharField(required=False)
  162. data = {'first_name': u'John', 'last_name': u'Lennon'}
  163. f = OptionalPersonForm(data)
  164. self.assertTrue(f.is_valid())
  165. self.assertEqual(f.cleaned_data['nick_name'], u'')
  166. self.assertEqual(f.cleaned_data['first_name'], u'John')
  167. self.assertEqual(f.cleaned_data['last_name'], u'Lennon')
  168. # For DateFields, it's set to None.
  169. class OptionalPersonForm(Form):
  170. first_name = CharField()
  171. last_name = CharField()
  172. birth_date = DateField(required=False)
  173. data = {'first_name': u'John', 'last_name': u'Lennon'}
  174. f = OptionalPersonForm(data)
  175. self.assertTrue(f.is_valid())
  176. self.assertEqual(f.cleaned_data['birth_date'], None)
  177. self.assertEqual(f.cleaned_data['first_name'], u'John')
  178. self.assertEqual(f.cleaned_data['last_name'], u'Lennon')
  179. def test_auto_id(self):
  180. # "auto_id" tells the Form to add an "id" attribute to each form element.
  181. # If it's a string that contains '%s', Django will use that as a format string
  182. # into which the field's name will be inserted. It will also put a <label> around
  183. # the human-readable labels for a field.
  184. p = Person(auto_id='%s_id')
  185. self.assertEqual(p.as_table(), """<tr><th><label for="first_name_id">First name:</label></th><td><input type="text" name="first_name" id="first_name_id" /></td></tr>
  186. <tr><th><label for="last_name_id">Last name:</label></th><td><input type="text" name="last_name" id="last_name_id" /></td></tr>
  187. <tr><th><label for="birthday_id">Birthday:</label></th><td><input type="text" name="birthday" id="birthday_id" /></td></tr>""")
  188. self.assertEqual(p.as_ul(), """<li><label for="first_name_id">First name:</label> <input type="text" name="first_name" id="first_name_id" /></li>
  189. <li><label for="last_name_id">Last name:</label> <input type="text" name="last_name" id="last_name_id" /></li>
  190. <li><label for="birthday_id">Birthday:</label> <input type="text" name="birthday" id="birthday_id" /></li>""")
  191. self.assertEqual(p.as_p(), """<p><label for="first_name_id">First name:</label> <input type="text" name="first_name" id="first_name_id" /></p>
  192. <p><label for="last_name_id">Last name:</label> <input type="text" name="last_name" id="last_name_id" /></p>
  193. <p><label for="birthday_id">Birthday:</label> <input type="text" name="birthday" id="birthday_id" /></p>""")
  194. def test_auto_id_true(self):
  195. # If auto_id is any True value whose str() does not contain '%s', the "id"
  196. # attribute will be the name of the field.
  197. p = Person(auto_id=True)
  198. self.assertEqual(p.as_ul(), """<li><label for="first_name">First name:</label> <input type="text" name="first_name" id="first_name" /></li>
  199. <li><label for="last_name">Last name:</label> <input type="text" name="last_name" id="last_name" /></li>
  200. <li><label for="birthday">Birthday:</label> <input type="text" name="birthday" id="birthday" /></li>""")
  201. def test_auto_id_false(self):
  202. # If auto_id is any False value, an "id" attribute won't be output unless it
  203. # was manually entered.
  204. p = Person(auto_id=False)
  205. self.assertEqual(p.as_ul(), """<li>First name: <input type="text" name="first_name" /></li>
  206. <li>Last name: <input type="text" name="last_name" /></li>
  207. <li>Birthday: <input type="text" name="birthday" /></li>""")
  208. def test_id_on_field(self):
  209. # In this example, auto_id is False, but the "id" attribute for the "first_name"
  210. # field is given. Also note that field gets a <label>, while the others don't.
  211. p = PersonNew(auto_id=False)
  212. self.assertEqual(p.as_ul(), """<li><label for="first_name_id">First name:</label> <input type="text" id="first_name_id" name="first_name" /></li>
  213. <li>Last name: <input type="text" name="last_name" /></li>
  214. <li>Birthday: <input type="text" name="birthday" /></li>""")
  215. def test_auto_id_on_form_and_field(self):
  216. # If the "id" attribute is specified in the Form and auto_id is True, the "id"
  217. # attribute in the Form gets precedence.
  218. p = PersonNew(auto_id=True)
  219. self.assertEqual(p.as_ul(), """<li><label for="first_name_id">First name:</label> <input type="text" id="first_name_id" name="first_name" /></li>
  220. <li><label for="last_name">Last name:</label> <input type="text" name="last_name" id="last_name" /></li>
  221. <li><label for="birthday">Birthday:</label> <input type="text" name="birthday" id="birthday" /></li>""")
  222. def test_various_boolean_values(self):
  223. class SignupForm(Form):
  224. email = EmailField()
  225. get_spam = BooleanField()
  226. f = SignupForm(auto_id=False)
  227. self.assertEqual(str(f['email']), '<input type="text" name="email" />')
  228. self.assertEqual(str(f['get_spam']), '<input type="checkbox" name="get_spam" />')
  229. f = SignupForm({'email': 'test@example.com', 'get_spam': True}, auto_id=False)
  230. self.assertEqual(str(f['email']), '<input type="text" name="email" value="test@example.com" />')
  231. self.assertEqual(str(f['get_spam']), '<input checked="checked" type="checkbox" name="get_spam" />')
  232. # 'True' or 'true' should be rendered without a value attribute
  233. f = SignupForm({'email': 'test@example.com', 'get_spam': 'True'}, auto_id=False)
  234. self.assertEqual(str(f['get_spam']), '<input checked="checked" type="checkbox" name="get_spam" />')
  235. f = SignupForm({'email': 'test@example.com', 'get_spam': 'true'}, auto_id=False)
  236. self.assertEqual(str(f['get_spam']), '<input checked="checked" type="checkbox" name="get_spam" />')
  237. # A value of 'False' or 'false' should be rendered unchecked
  238. f = SignupForm({'email': 'test@example.com', 'get_spam': 'False'}, auto_id=False)
  239. self.assertEqual(str(f['get_spam']), '<input type="checkbox" name="get_spam" />')
  240. f = SignupForm({'email': 'test@example.com', 'get_spam': 'false'}, auto_id=False)
  241. self.assertEqual(str(f['get_spam']), '<input type="checkbox" name="get_spam" />')
  242. def test_widget_output(self):
  243. # Any Field can have a Widget class passed to its constructor:
  244. class ContactForm(Form):
  245. subject = CharField()
  246. message = CharField(widget=Textarea)
  247. f = ContactForm(auto_id=False)
  248. self.assertEqual(str(f['subject']), '<input type="text" name="subject" />')
  249. self.assertEqual(str(f['message']), '<textarea rows="10" cols="40" name="message"></textarea>')
  250. # as_textarea(), as_text() and as_hidden() are shortcuts for changing the output
  251. # widget type:
  252. self.assertEqual(f['subject'].as_textarea(), u'<textarea rows="10" cols="40" name="subject"></textarea>')
  253. self.assertEqual(f['message'].as_text(), u'<input type="text" name="message" />')
  254. self.assertEqual(f['message'].as_hidden(), u'<input type="hidden" name="message" />')
  255. # The 'widget' parameter to a Field can also be an instance:
  256. class ContactForm(Form):
  257. subject = CharField()
  258. message = CharField(widget=Textarea(attrs={'rows': 80, 'cols': 20}))
  259. f = ContactForm(auto_id=False)
  260. self.assertEqual(str(f['message']), '<textarea rows="80" cols="20" name="message"></textarea>')
  261. # Instance-level attrs are *not* carried over to as_textarea(), as_text() and
  262. # as_hidden():
  263. self.assertEqual(f['message'].as_text(), u'<input type="text" name="message" />')
  264. f = ContactForm({'subject': 'Hello', 'message': 'I love you.'}, auto_id=False)
  265. self.assertEqual(f['subject'].as_textarea(), u'<textarea rows="10" cols="40" name="subject">Hello</textarea>')
  266. self.assertEqual(f['message'].as_text(), u'<input type="text" name="message" value="I love you." />')
  267. self.assertEqual(f['message'].as_hidden(), u'<input type="hidden" name="message" value="I love you." />')
  268. def test_forms_with_choices(self):
  269. # For a form with a <select>, use ChoiceField:
  270. class FrameworkForm(Form):
  271. name = CharField()
  272. language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')])
  273. f = FrameworkForm(auto_id=False)
  274. self.assertEqual(str(f['language']), """<select name="language">
  275. <option value="P">Python</option>
  276. <option value="J">Java</option>
  277. </select>""")
  278. f = FrameworkForm({'name': 'Django', 'language': 'P'}, auto_id=False)
  279. self.assertEqual(str(f['language']), """<select name="language">
  280. <option value="P" selected="selected">Python</option>
  281. <option value="J">Java</option>
  282. </select>""")
  283. # A subtlety: If one of the choices' value is the empty string and the form is
  284. # unbound, then the <option> for the empty-string choice will get selected="selected".
  285. class FrameworkForm(Form):
  286. name = CharField()
  287. language = ChoiceField(choices=[('', '------'), ('P', 'Python'), ('J', 'Java')])
  288. f = FrameworkForm(auto_id=False)
  289. self.assertEqual(str(f['language']), """<select name="language">
  290. <option value="" selected="selected">------</option>
  291. <option value="P">Python</option>
  292. <option value="J">Java</option>
  293. </select>""")
  294. # You can specify widget attributes in the Widget constructor.
  295. class FrameworkForm(Form):
  296. name = CharField()
  297. language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')], widget=Select(attrs={'class': 'foo'}))
  298. f = FrameworkForm(auto_id=False)
  299. self.assertEqual(str(f['language']), """<select class="foo" name="language">
  300. <option value="P">Python</option>
  301. <option value="J">Java</option>
  302. </select>""")
  303. f = FrameworkForm({'name': 'Django', 'language': 'P'}, auto_id=False)
  304. self.assertEqual(str(f['language']), """<select class="foo" name="language">
  305. <option value="P" selected="selected">Python</option>
  306. <option value="J">Java</option>
  307. </select>""")
  308. # When passing a custom widget instance to ChoiceField, note that setting
  309. # 'choices' on the widget is meaningless. The widget will use the choices
  310. # defined on the Field, not the ones defined on the Widget.
  311. class FrameworkForm(Form):
  312. name = CharField()
  313. language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')], widget=Select(choices=[('R', 'Ruby'), ('P', 'Perl')], attrs={'class': 'foo'}))
  314. f = FrameworkForm(auto_id=False)
  315. self.assertEqual(str(f['language']), """<select class="foo" name="language">
  316. <option value="P">Python</option>
  317. <option value="J">Java</option>
  318. </select>""")
  319. f = FrameworkForm({'name': 'Django', 'language': 'P'}, auto_id=False)
  320. self.assertEqual(str(f['language']), """<select class="foo" name="language">
  321. <option value="P" selected="selected">Python</option>
  322. <option value="J">Java</option>
  323. </select>""")
  324. # You can set a ChoiceField's choices after the fact.
  325. class FrameworkForm(Form):
  326. name = CharField()
  327. language = ChoiceField()
  328. f = FrameworkForm(auto_id=False)
  329. self.assertEqual(str(f['language']), """<select name="language">
  330. </select>""")
  331. f.fields['language'].choices = [('P', 'Python'), ('J', 'Java')]
  332. self.assertEqual(str(f['language']), """<select name="language">
  333. <option value="P">Python</option>
  334. <option value="J">Java</option>
  335. </select>""")
  336. def test_forms_with_radio(self):
  337. # Add widget=RadioSelect to use that widget with a ChoiceField.
  338. class FrameworkForm(Form):
  339. name = CharField()
  340. language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')], widget=RadioSelect)
  341. f = FrameworkForm(auto_id=False)
  342. self.assertEqual(str(f['language']), """<ul>
  343. <li><label><input type="radio" name="language" value="P" /> Python</label></li>
  344. <li><label><input type="radio" name="language" value="J" /> Java</label></li>
  345. </ul>""")
  346. self.assertEqual(f.as_table(), """<tr><th>Name:</th><td><input type="text" name="name" /></td></tr>
  347. <tr><th>Language:</th><td><ul>
  348. <li><label><input type="radio" name="language" value="P" /> Python</label></li>
  349. <li><label><input type="radio" name="language" value="J" /> Java</label></li>
  350. </ul></td></tr>""")
  351. self.assertEqual(f.as_ul(), """<li>Name: <input type="text" name="name" /></li>
  352. <li>Language: <ul>
  353. <li><label><input type="radio" name="language" value="P" /> Python</label></li>
  354. <li><label><input type="radio" name="language" value="J" /> Java</label></li>
  355. </ul></li>""")
  356. # Regarding auto_id and <label>, RadioSelect is a special case. Each radio button
  357. # gets a distinct ID, formed by appending an underscore plus the button's
  358. # zero-based index.
  359. f = FrameworkForm(auto_id='id_%s')
  360. self.assertEqual(str(f['language']), """<ul>
  361. <li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" /> Python</label></li>
  362. <li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" /> Java</label></li>
  363. </ul>""")
  364. # When RadioSelect is used with auto_id, and the whole form is printed using
  365. # either as_table() or as_ul(), the label for the RadioSelect will point to the
  366. # ID of the *first* radio button.
  367. self.assertEqual(f.as_table(), """<tr><th><label for="id_name">Name:</label></th><td><input type="text" name="name" id="id_name" /></td></tr>
  368. <tr><th><label for="id_language_0">Language:</label></th><td><ul>
  369. <li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" /> Python</label></li>
  370. <li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" /> Java</label></li>
  371. </ul></td></tr>""")
  372. self.assertEqual(f.as_ul(), """<li><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" /></li>
  373. <li><label for="id_language_0">Language:</label> <ul>
  374. <li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" /> Python</label></li>
  375. <li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" /> Java</label></li>
  376. </ul></li>""")
  377. self.assertEqual(f.as_p(), """<p><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" /></p>
  378. <p><label for="id_language_0">Language:</label> <ul>
  379. <li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" /> Python</label></li>
  380. <li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" /> Java</label></li>
  381. </ul></p>""")
  382. def test_forms_wit_hmultiple_choice(self):
  383. # MultipleChoiceField is a special case, as its data is required to be a list:
  384. class SongForm(Form):
  385. name = CharField()
  386. composers = MultipleChoiceField()
  387. f = SongForm(auto_id=False)
  388. self.assertEqual(str(f['composers']), """<select multiple="multiple" name="composers">
  389. </select>""")
  390. class SongForm(Form):
  391. name = CharField()
  392. composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')])
  393. f = SongForm(auto_id=False)
  394. self.assertEqual(str(f['composers']), """<select multiple="multiple" name="composers">
  395. <option value="J">John Lennon</option>
  396. <option value="P">Paul McCartney</option>
  397. </select>""")
  398. f = SongForm({'name': 'Yesterday', 'composers': ['P']}, auto_id=False)
  399. self.assertEqual(str(f['name']), '<input type="text" name="name" value="Yesterday" />')
  400. self.assertEqual(str(f['composers']), """<select multiple="multiple" name="composers">
  401. <option value="J">John Lennon</option>
  402. <option value="P" selected="selected">Paul McCartney</option>
  403. </select>""")
  404. def test_hidden_data(self):
  405. class SongForm(Form):
  406. name = CharField()
  407. composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')])
  408. # MultipleChoiceField rendered as_hidden() is a special case. Because it can
  409. # have multiple values, its as_hidden() renders multiple <input type="hidden">
  410. # tags.
  411. f = SongForm({'name': 'Yesterday', 'composers': ['P']}, auto_id=False)
  412. self.assertEqual(f['composers'].as_hidden(), '<input type="hidden" name="composers" value="P" />')
  413. f = SongForm({'name': 'From Me To You', 'composers': ['P', 'J']}, auto_id=False)
  414. self.assertEqual(f['composers'].as_hidden(), """<input type="hidden" name="composers" value="P" />
  415. <input type="hidden" name="composers" value="J" />""")
  416. # DateTimeField rendered as_hidden() is special too
  417. class MessageForm(Form):
  418. when = SplitDateTimeField()
  419. f = MessageForm({'when_0': '1992-01-01', 'when_1': '01:01'})
  420. self.assertTrue(f.is_valid())
  421. self.assertEqual(str(f['when']), '<input type="text" name="when_0" value="1992-01-01" id="id_when_0" /><input type="text" name="when_1" value="01:01" id="id_when_1" />')
  422. self.assertEqual(f['when'].as_hidden(), '<input type="hidden" name="when_0" value="1992-01-01" id="id_when_0" /><input type="hidden" name="when_1" value="01:01" id="id_when_1" />')
  423. def test_mulitple_choice_checkbox(self):
  424. # MultipleChoiceField can also be used with the CheckboxSelectMultiple widget.
  425. class SongForm(Form):
  426. name = CharField()
  427. composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=CheckboxSelectMultiple)
  428. f = SongForm(auto_id=False)
  429. self.assertEqual(str(f['composers']), """<ul>
  430. <li><label><input type="checkbox" name="composers" value="J" /> John Lennon</label></li>
  431. <li><label><input type="checkbox" name="composers" value="P" /> Paul McCartney</label></li>
  432. </ul>""")
  433. f = SongForm({'composers': ['J']}, auto_id=False)
  434. self.assertEqual(str(f['composers']), """<ul>
  435. <li><label><input checked="checked" type="checkbox" name="composers" value="J" /> John Lennon</label></li>
  436. <li><label><input type="checkbox" name="composers" value="P" /> Paul McCartney</label></li>
  437. </ul>""")
  438. f = SongForm({'composers': ['J', 'P']}, auto_id=False)
  439. self.assertEqual(str(f['composers']), """<ul>
  440. <li><label><input checked="checked" type="checkbox" name="composers" value="J" /> John Lennon</label></li>
  441. <li><label><input checked="checked" type="checkbox" name="composers" value="P" /> Paul McCartney</label></li>
  442. </ul>""")
  443. def test_checkbox_auto_id(self):
  444. # Regarding auto_id, CheckboxSelectMultiple is a special case. Each checkbox
  445. # gets a distinct ID, formed by appending an underscore plus the checkbox's
  446. # zero-based index.
  447. class SongForm(Form):
  448. name = CharField()
  449. composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=CheckboxSelectMultiple)
  450. f = SongForm(auto_id='%s_id')
  451. self.assertEqual(str(f['composers']), """<ul>
  452. <li><label for="composers_id_0"><input type="checkbox" name="composers" value="J" id="composers_id_0" /> John Lennon</label></li>
  453. <li><label for="composers_id_1"><input type="checkbox" name="composers" value="P" id="composers_id_1" /> Paul McCartney</label></li>
  454. </ul>""")
  455. def test_multiple_choice_list_data(self):
  456. # Data for a MultipleChoiceField should be a list. QueryDict, MultiValueDict and
  457. # MergeDict (when created as a merge of MultiValueDicts) conveniently work with
  458. # this.
  459. class SongForm(Form):
  460. name = CharField()
  461. composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=CheckboxSelectMultiple)
  462. data = {'name': 'Yesterday', 'composers': ['J', 'P']}
  463. f = SongForm(data)
  464. self.assertEqual(f.errors, {})
  465. data = QueryDict('name=Yesterday&composers=J&composers=P')
  466. f = SongForm(data)
  467. self.assertEqual(f.errors, {})
  468. data = MultiValueDict(dict(name=['Yesterday'], composers=['J', 'P']))
  469. f = SongForm(data)
  470. self.assertEqual(f.errors, {})
  471. data = MergeDict(MultiValueDict(dict(name=['Yesterday'], composers=['J', 'P'])))
  472. f = SongForm(data)
  473. self.assertEqual(f.errors, {})
  474. def test_multiple_hidden(self):
  475. class SongForm(Form):
  476. name = CharField()
  477. composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=CheckboxSelectMultiple)
  478. # The MultipleHiddenInput widget renders multiple values as hidden fields.
  479. class SongFormHidden(Form):
  480. name = CharField()
  481. composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=MultipleHiddenInput)
  482. f = SongFormHidden(MultiValueDict(dict(name=['Yesterday'], composers=['J', 'P'])), auto_id=False)
  483. self.assertEqual(f.as_ul(), """<li>Name: <input type="text" name="name" value="Yesterday" /><input type="hidden" name="composers" value="J" />
  484. <input type="hidden" name="composers" value="P" /></li>""")
  485. # When using CheckboxSelectMultiple, the framework expects a list of input and
  486. # returns a list of input.
  487. f = SongForm({'name': 'Yesterday'}, auto_id=False)
  488. self.assertEqual(f.errors['composers'], [u'This field is required.'])
  489. f = SongForm({'name': 'Yesterday', 'composers': ['J']}, auto_id=False)
  490. self.assertEqual(f.errors, {})
  491. self.assertEqual(f.cleaned_data['composers'], [u'J'])
  492. self.assertEqual(f.cleaned_data['name'], u'Yesterday')
  493. f = SongForm({'name': 'Yesterday', 'composers': ['J', 'P']}, auto_id=False)
  494. self.assertEqual(f.errors, {})
  495. self.assertEqual(f.cleaned_data['composers'], [u'J', u'P'])
  496. self.assertEqual(f.cleaned_data['name'], u'Yesterday')
  497. def test_escaping(self):
  498. # Validation errors are HTML-escaped when output as HTML.
  499. class EscapingForm(Form):
  500. special_name = CharField(label="<em>Special</em> Field")
  501. special_safe_name = CharField(label=mark_safe("<em>Special</em> Field"))
  502. def clean_special_name(self):
  503. raise ValidationError("Something's wrong with '%s'" % self.cleaned_data['special_name'])
  504. def clean_special_safe_name(self):
  505. raise ValidationError(mark_safe("'<b>%s</b>' is a safe string" % self.cleaned_data['special_safe_name']))
  506. f = EscapingForm({'special_name': "Nothing to escape", 'special_safe_name': "Nothing to escape"}, auto_id=False)
  507. self.assertEqual(f.as_table(), """<tr><th>&lt;em&gt;Special&lt;/em&gt; Field:</th><td><ul class="errorlist"><li>Something&#39;s wrong with &#39;Nothing to escape&#39;</li></ul><input type="text" name="special_name" value="Nothing to escape" /></td></tr>
  508. <tr><th><em>Special</em> Field:</th><td><ul class="errorlist"><li>'<b>Nothing to escape</b>' is a safe string</li></ul><input type="text" name="special_safe_name" value="Nothing to escape" /></td></tr>""")
  509. f = EscapingForm({
  510. 'special_name': "Should escape < & > and <script>alert('xss')</script>",
  511. 'special_safe_name': "<i>Do not escape</i>"
  512. }, auto_id=False)
  513. self.assertEqual(f.as_table(), """<tr><th>&lt;em&gt;Special&lt;/em&gt; Field:</th><td><ul class="errorlist"><li>Something&#39;s wrong with &#39;Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#39;xss&#39;)&lt;/script&gt;&#39;</li></ul><input type="text" name="special_name" value="Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#39;xss&#39;)&lt;/script&gt;" /></td></tr>
  514. <tr><th><em>Special</em> Field:</th><td><ul class="errorlist"><li>'<b><i>Do not escape</i></b>' is a safe string</li></ul><input type="text" name="special_safe_name" value="&lt;i&gt;Do not escape&lt;/i&gt;" /></td></tr>""")
  515. def test_validating_multiple_fields(self):
  516. # There are a couple of ways to do multiple-field validation. If you want the
  517. # validation message to be associated with a particular field, implement the
  518. # clean_XXX() method on the Form, where XXX is the field name. As in
  519. # Field.clean(), the clean_XXX() method should return the cleaned value. In the
  520. # clean_XXX() method, you have access to self.cleaned_data, which is a dictionary
  521. # of all the data that has been cleaned *so far*, in order by the fields,
  522. # including the current field (e.g., the field XXX if you're in clean_XXX()).
  523. class UserRegistration(Form):
  524. username = CharField(max_length=10)
  525. password1 = CharField(widget=PasswordInput)
  526. password2 = CharField(widget=PasswordInput)
  527. def clean_password2(self):
  528. if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']:
  529. raise ValidationError(u'Please make sure your passwords match.')
  530. return self.cleaned_data['password2']
  531. f = UserRegistration(auto_id=False)
  532. self.assertEqual(f.errors, {})
  533. f = UserRegistration({}, auto_id=False)
  534. self.assertEqual(f.errors['username'], [u'This field is required.'])
  535. self.assertEqual(f.errors['password1'], [u'This field is required.'])
  536. self.assertEqual(f.errors['password2'], [u'This field is required.'])
  537. f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)
  538. self.assertEqual(f.errors['password2'], [u'Please make sure your passwords match.'])
  539. f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'foo'}, auto_id=False)
  540. self.assertEqual(f.errors, {})
  541. self.assertEqual(f.cleaned_data['username'], u'adrian')
  542. self.assertEqual(f.cleaned_data['password1'], u'foo')
  543. self.assertEqual(f.cleaned_data['password2'], u'foo')
  544. # Another way of doing multiple-field validation is by implementing the
  545. # Form's clean() method. If you do this, any ValidationError raised by that
  546. # method will not be associated with a particular field; it will have a
  547. # special-case association with the field named '__all__'.
  548. # Note that in Form.clean(), you have access to self.cleaned_data, a dictionary of
  549. # all the fields/values that have *not* raised a ValidationError. Also note
  550. # Form.clean() is required to return a dictionary of all clean data.
  551. class UserRegistration(Form):
  552. username = CharField(max_length=10)
  553. password1 = CharField(widget=PasswordInput)
  554. password2 = CharField(widget=PasswordInput)
  555. def clean(self):
  556. if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']:
  557. raise ValidationError(u'Please make sure your passwords match.')
  558. return self.cleaned_data
  559. f = UserRegistration(auto_id=False)
  560. self.assertEqual(f.errors, {})
  561. f = UserRegistration({}, auto_id=False)
  562. self.assertEqual(f.as_table(), """<tr><th>Username:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="username" maxlength="10" /></td></tr>
  563. <tr><th>Password1:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="password" name="password1" /></td></tr>
  564. <tr><th>Password2:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="password" name="password2" /></td></tr>""")
  565. self.assertEqual(f.errors['username'], [u'This field is required.'])
  566. self.assertEqual(f.errors['password1'], [u'This field is required.'])
  567. self.assertEqual(f.errors['password2'], [u'This field is required.'])
  568. f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)
  569. self.assertEqual(f.errors['__all__'], [u'Please make sure your passwords match.'])
  570. self.assertEqual(f.as_table(), """<tr><td colspan="2"><ul class="errorlist"><li>Please make sure your passwords match.</li></ul></td></tr>
  571. <tr><th>Username:</th><td><input type="text" name="username" value="adrian" maxlength="10" /></td></tr>
  572. <tr><th>Password1:</th><td><input type="password" name="password1" /></td></tr>
  573. <tr><th>Password2:</th><td><input type="password" name="password2" /></td></tr>""")
  574. self.assertEqual(f.as_ul(), """<li><ul class="errorlist"><li>Please make sure your passwords match.</li></ul></li>
  575. <li>Username: <input type="text" name="username" value="adrian" maxlength="10" /></li>
  576. <li>Password1: <input type="password" name="password1" /></li>
  577. <li>Password2: <input type="password" name="password2" /></li>""")
  578. f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'foo'}, auto_id=False)
  579. self.assertEqual(f.errors, {})
  580. self.assertEqual(f.cleaned_data['username'], u'adrian')
  581. self.assertEqual(f.cleaned_data['password1'], u'foo')
  582. self.assertEqual(f.cleaned_data['password2'], u'foo')
  583. def test_dynamic_construction(self):
  584. # It's possible to construct a Form dynamically by adding to the self.fields
  585. # dictionary in __init__(). Don't forget to call Form.__init__() within the
  586. # subclass' __init__().
  587. class Person(Form):
  588. first_name = CharField()
  589. last_name = CharField()
  590. def __init__(self, *args, **kwargs):
  591. super(Person, self).__init__(*args, **kwargs)
  592. self.fields['birthday'] = DateField()
  593. p = Person(auto_id=False)
  594. self.assertEqual(p.as_table(), """<tr><th>First name:</th><td><input type="text" name="first_name" /></td></tr>
  595. <tr><th>Last name:</th><td><input type="text" name="last_name" /></td></tr>
  596. <tr><th>Birthday:</th><td><input type="text" name="birthday" /></td></tr>""")
  597. # Instances of a dynamic Form do not persist fields from one Form instance to
  598. # the next.
  599. class MyForm(Form):
  600. def __init__(self, data=None, auto_id=False, field_list=[]):
  601. Form.__init__(self, data, auto_id=auto_id)
  602. for field in field_list:
  603. self.fields[field[0]] = field[1]
  604. field_list = [('field1', CharField()), ('field2', CharField())]
  605. my_form = MyForm(field_list=field_list)
  606. self.assertEqual(my_form.as_table(), """<tr><th>Field1:</th><td><input type="text" name="field1" /></td></tr>
  607. <tr><th>Field2:</th><td><input type="text" name="field2" /></td></tr>""")
  608. field_list = [('field3', CharField()), ('field4', CharField())]
  609. my_form = MyForm(field_list=field_list)
  610. self.assertEqual(my_form.as_table(), """<tr><th>Field3:</th><td><input type="text" name="field3" /></td></tr>
  611. <tr><th>Field4:</th><td><input type="text" name="field4" /></td></tr>""")
  612. class MyForm(Form):
  613. default_field_1 = CharField()
  614. default_field_2 = CharField()
  615. def __init__(self, data=None, auto_id=False, field_list=[]):
  616. Form.__init__(self, data, auto_id=auto_id)
  617. for field in field_list:
  618. self.fields[field[0]] = field[1]
  619. field_list = [('field1', CharField()), ('field2', CharField())]
  620. my_form = MyForm(field_list=field_list)
  621. self.assertEqual(my_form.as_table(), """<tr><th>Default field 1:</th><td><input type="text" name="default_field_1" /></td></tr>
  622. <tr><th>Default field 2:</th><td><input type="text" name="default_field_2" /></td></tr>
  623. <tr><th>Field1:</th><td><input type="text" name="field1" /></td></tr>
  624. <tr><th>Field2:</th><td><input type="text" name="field2" /></td></tr>""")
  625. field_list = [('field3', CharField()), ('field4', CharField())]
  626. my_form = MyForm(field_list=field_list)
  627. self.assertEqual(my_form.as_table(), """<tr><th>Default field 1:</th><td><input type="text" name="default_field_1" /></td></tr>
  628. <tr><th>Default field 2:</th><td><input type="text" name="default_field_2" /></td></tr>
  629. <tr><th>Field3:</th><td><input type="text" name="field3" /></td></tr>
  630. <tr><th>Field4:</th><td><input type="text" name="field4" /></td></tr>""")
  631. # Similarly, changes to field attributes do not persist from one Form instance
  632. # to the next.
  633. class Person(Form):
  634. first_name = CharField(required=False)
  635. last_name = CharField(required=False)
  636. def __init__(self, names_required=False, *args, **kwargs):
  637. super(Person, self).__init__(*args, **kwargs)
  638. if names_required:
  639. self.fields['first_name'].required = True
  640. self.fields['first_name'].widget.attrs['class'] = 'required'
  641. self.fields['last_name'].required = True
  642. self.fields['last_name'].widget.attrs['class'] = 'required'
  643. f = Person(names_required=False)
  644. self.assertEqual(f['first_name'].field.required, f['last_name'].field.required, (False, False))
  645. self.assertEqual(f['first_name'].field.widget.attrs, f['last_name'].field.widget.attrs, ({}, {}))
  646. f = Person(names_required=True)
  647. self.assertEqual(f['first_name'].field.required, f['last_name'].field.required, (True, True))
  648. self.assertEqual(f['first_name'].field.widget.attrs, f['last_name'].field.widget.attrs, ({'class': 'required'}, {'class': 'required'}))
  649. f = Person(names_required=False)
  650. self.assertEqual(f['first_name'].field.required, f['last_name'].field.required, (False, False))
  651. self.assertEqual(f['first_name'].field.widget.attrs, f['last_name'].field.widget.attrs, ({}, {}))
  652. class Person(Form):
  653. first_name = CharField(max_length=30)
  654. last_name = CharField(max_length=30)
  655. def __init__(self, name_max_length=None, *args, **kwargs):
  656. super(Person, self).__init__(*args, **kwargs)
  657. if name_max_length:
  658. self.fields['first_name'].max_length = name_max_length
  659. self.fields['last_name'].max_length = name_max_length
  660. f = Person(name_max_length=None)
  661. self.assertEqual(f['first_name'].field.max_length, f['last_name'].field.max_length, (30, 30))
  662. f = Person(name_max_length=20)
  663. self.assertEqual(f['first_name'].field.max_length, f['last_name'].field.max_length, (20, 20))
  664. f = Person(name_max_length=None)
  665. self.assertEqual(f['first_name'].field.max_length, f['last_name'].field.max_length, (30, 30))
  666. def test_hidden_widget(self):
  667. # HiddenInput widgets are displayed differently in the as_table(), as_ul())
  668. # and as_p() output of a Form -- their verbose names are not displayed, and a
  669. # separate row is not displayed. They're displayed in the last row of the
  670. # form, directly after that row's form element.
  671. class Person(Form):
  672. first_name = CharField()
  673. last_name = CharField()
  674. hidden_text = CharField(widget=HiddenInput)
  675. birthday = DateField()
  676. p = Person(auto_id=False)
  677. self.assertEqual(p.as_table(), """<tr><th>First name:</th><td><input type="text" name="first_name" /></td></tr>
  678. <tr><th>Last name:</th><td><input type="text" name="last_name" /></td></tr>
  679. <tr><th>Birthday:</th><td><input type="text" name="birthday" /><input type="hidden" name="hidden_text" /></td></tr>""")
  680. self.assertEqual(p.as_ul(), """<li>First name: <input type="text" name="first_name" /></li>
  681. <li>Last name: <input type="text" name="last_name" /></li>
  682. <li>Birthday: <input type="text" name="birthday" /><input type="hidden" name="hidden_text" /></li>""")
  683. self.assertEqual(p.as_p(), """<p>First name: <input type="text" name="first_name" /></p>
  684. <p>Last name: <input type="text" name="last_name" /></p>
  685. <p>Birthday: <input type="text" name="birthday" /><input type="hidden" name="hidden_text" /></p>""")
  686. # With auto_id set, a HiddenInput still gets an ID, but it doesn't get a label.
  687. p = Person(auto_id='id_%s')
  688. self.assertEqual(p.as_table(), """<tr><th><label for="id_first_name">First name:</label></th><td><input type="text" name="first_name" id="id_first_name" /></td></tr>
  689. <tr><th><label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" id="id_last_name" /></td></tr>
  690. <tr><th><label for="id_birthday">Birthday:</label></th><td><input type="text" name="birthday" id="id_birthday" /><input type="hidden" name="hidden_text" id="id_hidden_text" /></td></tr>""")
  691. self.assertEqual(p.as_ul(), """<li><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" /></li>
  692. <li><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></li>
  693. <li><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /><input type="hidden" name="hidden_text" id="id_hidden_text" /></li>""")
  694. self.assertEqual(p.as_p(), """<p><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" /></p>
  695. <p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></p>
  696. <p><label for="id_b…

Large files files are truncated, but you can click here to view the full file