PageRenderTime 65ms CodeModel.GetById 22ms 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
  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_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /><input type="hidden" name="hidden_text" id="id_hidden_text" /></p>""")
  697. # If a field with a HiddenInput has errors, the as_table() and as_ul() output
  698. # will include the error message(s) with the text "(Hidden field [fieldname]) "
  699. # prepended. This message is displayed at the top of the output, regardless of
  700. # its field's order in the form.
  701. p = Person({'first_name': 'John', 'last_name': 'Lennon', 'birthday': '1940-10-9'}, auto_id=False)
  702. self.assertEqual(p.as_table(), """<tr><td colspan="2"><ul class="errorlist"><li>(Hidden field hidden_text) This field is required.</li></ul></td></tr>
  703. <tr><th>First name:</th><td><input type="text" name="first_name" value="John" /></td></tr>
  704. <tr><th>Last name:</th><td><input type="text" name="last_name" value="Lennon" /></td></tr>
  705. <tr><th>Birthday:</th><td><input type="text" name="birthday" value="1940-10-9" /><input type="hidden" name="hidden_text" /></td></tr>""")
  706. self.assertEqual(p.as_ul(), """<li><ul class="errorlist"><li>(Hidden field hidden_text) This field is required.</li></ul></li>
  707. <li>First name: <input type="text" name="first_name" value="John" /></li>
  708. <li>Last name: <input type="text" name="last_name" value="Lennon" /></li>
  709. <li>Birthday: <input type="text" name="birthday" value="1940-10-9" /><input type="hidden" name="hidden_text" /></li>""")
  710. self.assertEqual(p.as_p(), """<ul class="errorlist"><li>(Hidden field hidden_text) This field is required.</li></ul>
  711. <p>First name: <input type="text" name="first_name" value="John" /></p>
  712. <p>Last name: <input type="text" name="last_name" value="Lennon" /></p>
  713. <p>Birthday: <input type="text" name="birthday" value="1940-10-9" /><input type="hidden" name="hidden_text" /></p>""")
  714. # A corner case: It's possible for a form to have only HiddenInputs.
  715. class TestForm(Form):
  716. foo = CharField(widget=HiddenInput)
  717. bar = CharField(widget=HiddenInput)
  718. p = TestForm(auto_id=False)
  719. self.assertEqual(p.as_table(), '<input type="hidden" name="foo" /><input type="hidden" name="bar" />')
  720. self.assertEqual(p.as_ul(), '<input type="hidden" name="foo" /><input type="hidden" name="bar" />')
  721. self.assertEqual(p.as_p(), '<input type="hidden" name="foo" /><input type="hidden" name="bar" />')
  722. def test_field_order(self):
  723. # A Form's fields are displayed in the same order in which they were defined.
  724. class TestForm(Form):
  725. field1 = CharField()
  726. field2 = CharField()
  727. field3 = CharField()
  728. field4 = CharField()
  729. field5 = CharField()
  730. field6 = CharField()
  731. field7 = CharField()
  732. field8 = CharField()
  733. field9 = CharField()
  734. field10 = CharField()
  735. field11 = CharField()
  736. field12 = CharField()
  737. field13 = CharField()
  738. field14 = CharField()
  739. p = TestForm(auto_id=False)
  740. self.assertEqual(p.as_table(), """<tr><th>Field1:</th><td><input type="text" name="field1" /></td></tr>
  741. <tr><th>Field2:</th><td><input type="text" name="field2" /></td></tr>
  742. <tr><th>Field3:</th><td><input type="text" name="field3" /></td></tr>
  743. <tr><th>Field4:</th><td><input type="text" name="field4" /></td></tr>
  744. <tr><th>Field5:</th><td><input type="text" name="field5" /></td></tr>
  745. <tr><th>Field6:</th><td><input type="text" name="field6" /></td></tr>
  746. <tr><th>Field7:</th><td><input type="text" name="field7" /></td></tr>
  747. <tr><th>Field8:</th><td><input type="text" name="field8" /></td></tr>
  748. <tr><th>Field9:</th><td><input type="text" name="field9" /></td></tr>
  749. <tr><th>Field10:</th><td><input type="text" name="field10" /></td></tr>
  750. <tr><th>Field11:</th><td><input type="text" name="field11" /></td></tr>
  751. <tr><th>Field12:</th><td><input type="text" name="field12" /></td></tr>
  752. <tr><th>Field13:</th><td><input type="text" name="field13" /></td></tr>
  753. <tr><th>Field14:</th><td><input type="text" name="field14" /></td></tr>""")
  754. def test_form_html_attributes(self):
  755. # Some Field classes have an effect on the HTML attributes of their associated
  756. # Widget. If you set max_length in a CharField and its associated widget is
  757. # either a TextInput or PasswordInput, then the widget's rendered HTML will
  758. # include the "maxlength" attribute.
  759. class UserRegistration(Form):
  760. username = CharField(max_length=10) # uses TextInput by default
  761. password = CharField(max_length=10, widget=PasswordInput)
  762. realname = CharField(max_length=10, widget=TextInput) # redundantly define widget, just to test
  763. address = CharField() # no max_length defined here
  764. p = UserRegistration(auto_id=False)
  765. self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" /></li>
  766. <li>Password: <input type="password" name="password" maxlength="10" /></li>
  767. <li>Realname: <input type="text" name="realname" maxlength="10" /></li>
  768. <li>Address: <input type="text" name="address" /></li>""")
  769. # If you specify a custom "attrs" that includes the "maxlength" attribute,
  770. # the Field's max_length attribute will override whatever "maxlength" you specify
  771. # in "attrs".
  772. class UserRegistration(Form):
  773. username = CharField(max_length=10, widget=TextInput(attrs={'maxlength': 20}))
  774. password = CharField(max_length=10, widget=PasswordInput)
  775. p = UserRegistration(auto_id=False)
  776. self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" /></li>
  777. <li>Password: <input type="password" name="password" maxlength="10" /></li>""")
  778. def test_specifying_labels(self):
  779. # You can specify the label for a field by using the 'label' argument to a Field
  780. # class. If you don't specify 'label', Django will use the field name with
  781. # underscores converted to spaces, and the initial letter capitalized.
  782. class UserRegistration(Form):
  783. username = CharField(max_length=10, label='Your username')
  784. password1 = CharField(widget=PasswordInput)
  785. password2 = CharField(widget=PasswordInput, label='Password (again)')
  786. p = UserRegistration(auto_id=False)
  787. self.assertEqual(p.as_ul(), """<li>Your username: <input type="text" name="username" maxlength="10" /></li>
  788. <li>Password1: <input type="password" name="password1" /></li>
  789. <li>Password (again): <input type="password" name="password2" /></li>""")
  790. # Labels for as_* methods will only end in a colon if they don't end in other
  791. # punctuation already.
  792. class Questions(Form):
  793. q1 = CharField(label='The first question')
  794. q2 = CharField(label='What is your name?')
  795. q3 = CharField(label='The answer to life is:')
  796. q4 = CharField(label='Answer this question!')
  797. q5 = CharField(label='The last question. Period.')
  798. self.assertEqual(Questions(auto_id=False).as_p(), """<p>The first question: <input type="text" name="q1" /></p>
  799. <p>What is your name? <input type="text" name="q2" /></p>
  800. <p>The answer to life is: <input type="text" name="q3" /></p>
  801. <p>Answer this question! <input type="text" name="q4" /></p>
  802. <p>The last question. Period. <input type="text" name="q5" /></p>""")
  803. self.assertEqual(Questions().as_p(), """<p><label for="id_q1">The first question:</label> <input type="text" name="q1" id="id_q1" /></p>
  804. <p><label for="id_q2">What is your name?</label> <input type="text" name="q2" id="id_q2" /></p>
  805. <p><label for="id_q3">The answer to life is:</label> <input type="text" name="q3" id="id_q3" /></p>
  806. <p><label for="id_q4">Answer this question!</label> <input type="text" name="q4" id="id_q4" /></p>
  807. <p><label for="id_q5">The last question. Period.</label> <input type="text" name="q5" id="id_q5" /></p>""")
  808. # A label can be a Unicode object or a bytestring with special characters.
  809. class UserRegistration(Form):
  810. username = CharField(max_length=10, label='Š??Ž?žš?')
  811. password = CharField(widget=PasswordInput, label=u'\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111')
  812. p = UserRegistration(auto_id=False)
  813. self.assertEqual(p.as_ul(), u'<li>\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111: <input type="text" name="username" maxlength="10" /></li>\n<li>\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111: <input type="password" name="password" /></li>')
  814. # If a label is set to the empty string for a field, that field won't get a label.
  815. class UserRegistration(Form):
  816. username = CharField(max_length=10, label='')
  817. password = CharField(widget=PasswordInput)
  818. p = UserRegistration(auto_id=False)
  819. self.assertEqual(p.as_ul(), """<li> <input type="text" name="username" maxlength="10" /></li>
  820. <li>Password: <input type="password" name="password" /></li>""")
  821. p = UserRegistration(auto_id='id_%s')
  822. self.assertEqual(p.as_ul(), """<li> <input id="id_username" type="text" name="username" maxlength="10" /></li>
  823. <li><label for="id_password">Password:</label> <input type="password" name="password" id="id_password" /></li>""")
  824. # If label is None, Django will auto-create the label from the field name. This
  825. # is default behavior.
  826. class UserRegistration(Form):
  827. username = CharField(max_length=10, label=None)
  828. password = CharField(widget=PasswordInput)
  829. p = UserRegistration(auto_id=False)
  830. self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" /></li>
  831. <li>Password: <input type="password" name="password" /></li>""")
  832. p = UserRegistration(auto_id='id_%s')
  833. self.assertEqual(p.as_ul(), """<li><label for="id_username">Username:</label> <input id="id_username" type="text" name="username" maxlength="10" /></li>
  834. <li><label for="id_password">Password:</label> <input type="password" name="password" id="id_password" /></li>""")
  835. def test_label_suffix(self):
  836. # You can specify the 'label_suffix' argument to a Form class to modify the
  837. # punctuation symbol used at the end of a label. By default, the colon (:) is
  838. # used, and is only appended to the label if the label doesn't already end with a
  839. # punctuation symbol: ., !, ? or :. If you specify a different suffix, it will
  840. # be appended regardless of the last character of the label.
  841. class FavoriteForm(Form):
  842. color = CharField(label='Favorite color?')
  843. animal = CharField(label='Favorite animal')
  844. f = FavoriteForm(auto_id=False)
  845. self.assertEqual(f.as_ul(), """<li>Favorite color? <input type="text" name="color" /></li>
  846. <li>Favorite animal: <input type="text" name="animal" /></li>""")
  847. f = FavoriteForm(auto_id=False, label_suffix='?')
  848. self.assertEqual(f.as_ul(), """<li>Favorite color? <input type="text" name="color" /></li>
  849. <li>Favorite animal? <input type="text" name="animal" /></li>""")
  850. f = FavoriteForm(auto_id=False, label_suffix='')
  851. self.assertEqual(f.as_ul(), """<li>Favorite color? <input type="text" name="color" /></li>
  852. <li>Favorite animal <input type="text" name="animal" /></li>""")
  853. f = FavoriteForm(auto_id=False, label_suffix=u'\u2192')
  854. self.assertEqual(f.as_ul(), u'<li>Favorite color? <input type="text" name="color" /></li>\n<li>Favorite animal\u2192 <input type="text" name="animal" /></li>')
  855. def test_initial_data(self):
  856. # You can specify initial data for a field by using the 'initial' argument to a
  857. # Field class. This initial data is displayed when a Form is rendered with *no*
  858. # data. It is not displayed when a Form is rendered with any data (including an
  859. # empty dictionary). Also, the initial value is *not* used if data for a
  860. # particular required field isn't provided.
  861. class UserRegistration(Form):
  862. username = CharField(max_length=10, initial='django')
  863. password = CharField(widget=PasswordInput)
  864. # Here, we're not submitting any data, so the initial value will be displayed.)
  865. p = UserRegistration(auto_id=False)
  866. self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="django" maxlength="10" /></li>
  867. <li>Password: <input type="password" name="password" /></li>""")
  868. # Here, we're submitting data, so the initial value will *not* be displayed.
  869. p = UserRegistration({}, auto_id=False)
  870. self.assertEqual(p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul>Username: <input type="text" name="username" maxlength="10" /></li>
  871. <li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>""")
  872. p = UserRegistration({'username': u''}, auto_id=False)
  873. self.assertEqual(p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul>Username: <input type="text" name="username" maxlength="10" /></li>
  874. <li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>""")
  875. p = UserRegistration({'username': u'foo'}, auto_id=False)
  876. self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="foo" maxlength="10" /></li>
  877. <li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>""")
  878. # An 'initial' value is *not* used as a fallback if data is not provided. In this
  879. # example, we don't provide a value for 'username', and the form raises a
  880. # validation error rather than using the initial value for 'username'.
  881. p = UserRegistration({'password': 'secret'})
  882. self.assertEqual(p.errors['username'], [u'This field is required.'])
  883. self.assertFalse(p.is_valid())
  884. def test_dynamic_initial_data(self):
  885. # The previous technique dealt with "hard-coded" initial data, but it's also
  886. # possible to specify initial data after you've already created the Form class
  887. # (i.e., at runtime). Use the 'initial' parameter to the Form constructor. This
  888. # should be a dictionary containing initial values for one or more fields in the
  889. # form, keyed by field name.
  890. class UserRegistration(Form):
  891. username = CharField(max_length=10)
  892. password = CharField(widget=PasswordInput)
  893. # Here, we're not submitting any data, so the initial value will be displayed.)
  894. p = UserRegistration(initial={'username': 'django'}, auto_id=False)
  895. self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="django" maxlength="10" /></li>
  896. <li>Password: <input type="password" name="password" /></li>""")
  897. p = UserRegistration(initial={'username': 'stephane'}, auto_id=False)
  898. self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="stephane" maxlength="10" /></li>
  899. <li>Password: <input type="password" name="password" /></li>""")
  900. # The 'initial' parameter is meaningless if you pass data.
  901. p = UserRegistration({}, initial={'username': 'django'}, auto_id=False)
  902. self.assertEqual(p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul>Username: <input type="text" name="username" maxlength="10" /></li>
  903. <li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>""")
  904. p = UserRegistration({'username': u''}, initial={'username': 'django'}, auto_id=False)
  905. self.assertEqual(p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul>Username: <input type="text" name="username" maxlength="10" /></li>
  906. <li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>""")
  907. p = UserRegistration({'username': u'foo'}, initial={'username': 'django'}, auto_id=False)
  908. self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="foo" maxlength="10" /></li>
  909. <li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>""")
  910. # A dynamic 'initial' value is *not* used as a fallback if data is not provided.
  911. # In this example, we don't provide a value for 'username', and the form raises a
  912. # validation error rather than using the initial value for 'username'.
  913. p = UserRegistration({'password': 'secret'}, initial={'username': 'django'})
  914. self.assertEqual(p.errors['username'], [u'This field is required.'])
  915. self.assertFalse(p.is_valid())
  916. # If a Form defines 'initial' *and* 'initial' is passed as a parameter to Form(),
  917. # then the latter will get precedence.
  918. class UserRegistration(Form):
  919. username = CharField(max_length=10, initial='django')
  920. password = CharField(widget=PasswordInput)
  921. p = UserRegistration(initial={'username': 'babik'}, auto_id=False)
  922. self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="babik" maxlength="10" /></li>
  923. <li>Password: <input type="password" name="password" /></li>""")
  924. def test_callable_initial_data(self):
  925. # The previous technique dealt with raw values as initial data, but it's also
  926. # possible to specify callable data.
  927. class UserRegistration(Form):
  928. username = CharField(max_length=10)
  929. password = CharField(widget=PasswordInput)
  930. options = MultipleChoiceField(choices=[('f','foo'),('b','bar'),('w','whiz')])
  931. # We need to define functions that get called later.)
  932. def initial_django():
  933. return 'django'
  934. def initial_stephane():
  935. return 'stephane'
  936. def initial_options():
  937. return ['f','b']
  938. def initial_other_options():
  939. return ['b','w']
  940. # Here, we're not submitting any data, so the initial value will be displayed.)
  941. p = UserRegistration(initial={'username': initial_django, 'options': initial_options}, auto_id=False)
  942. self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="django" maxlength="10" /></li>
  943. <li>Password: <input type="password" name="password" /></li>
  944. <li>Options: <select multiple="multiple" name="options">
  945. <option value="f" selected="selected">foo</option>
  946. <option value="b" selected="selected">bar</option>
  947. <option value="w">whiz</option>
  948. </select></li>""")
  949. # The 'initial' parameter is meaningless if you pass data.
  950. p = UserRegistration({}, initial={'username': initial_django, 'options': initial_options}, auto_id=False)
  951. self.assertEqual(p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul>Username: <input type="text" name="username" maxlength="10" /></li>
  952. <li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>
  953. <li><ul class="errorlist"><li>This field is required.</li></ul>Options: <select multiple="multiple" name="options">
  954. <option value="f">foo</option>
  955. <option value="b">bar</option>
  956. <option value="w">whiz</option>
  957. </select></li>""")
  958. p = UserRegistration({'username': u''}, initial={'username': initial_django}, auto_id=False)
  959. self.assertEqual(p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul>Username: <input type="text" name="username" maxlength="10" /></li>
  960. <li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>
  961. <li><ul class="errorlist"><li>This field is required.</li></ul>Options: <select multiple="multiple" name="options">
  962. <option value="f">foo</option>
  963. <option value="b">bar</option>
  964. <option value="w">whiz</option>
  965. </select></li>""")
  966. p = UserRegistration({'username': u'foo', 'options':['f','b']}, initial={'username': initial_django}, auto_id=False)
  967. self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="foo" maxlength="10" /></li>
  968. <li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>
  969. <li>Options: <select multiple="multiple" name="options">
  970. <option value="f" selected="selected">foo</option>
  971. <option value="b" selected="selected">bar</option>
  972. <option value="w">whiz</option>
  973. </select></li>""")
  974. # A callable 'initial' value is *not* used as a fallback if data is not provided.
  975. # In this example, we don't provide a value for 'username', and the form raises a
  976. # validation error rather than using the initial value for 'username'.
  977. p = UserRegistration({'password': 'secret'}, initial={'username': initial_django, 'options': initial_options})
  978. self.assertEqual(p.errors['username'], [u'This field is required.'])
  979. self.assertFalse(p.is_valid())
  980. # If a Form defines 'initial' *and* 'initial' is passed as a parameter to Form(),
  981. # then the latter will get precedence.
  982. class UserRegistration(Form):
  983. username = CharField(max_length=10, initial=initial_django)
  984. password = CharField(widget=PasswordInput)
  985. options = MultipleChoiceField(choices=[('f','foo'),('b','bar'),('w','whiz')], initial=initial_other_options)
  986. p = UserRegistration(auto_id=False)
  987. self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="django" maxlength="10" /></li>
  988. <li>Password: <input type="password" name="password" /></li>
  989. <li>Options: <select multiple="multiple" name="options">
  990. <option value="f">foo</option>
  991. <option value="b" selected="selected">bar</option>
  992. <option value="w" selected="selected">whiz</option>
  993. </select></li>""")
  994. p = UserRegistration(initial={'username': initial_stephane, 'options': initial_options}, auto_id=False)
  995. self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="stephane" maxlength="10" /></li>
  996. <li>Password: <input type="password" name="password" /></li>
  997. <li>Options: <select multiple="multiple" name="options">
  998. <option value="f" selected="selected">foo</option>
  999. <option value="b" selected="selected">bar</option>
  1000. <option value="w">whiz</option>
  1001. </select></li>""")
  1002. def test_boundfield_values(self):
  1003. # It's possible to get to the value which would be used for rendering
  1004. # the widget for a field by using the BoundField's value method.
  1005. class UserRegistration(Form):
  1006. username = CharField(max_length=10, initial='djangonaut')
  1007. password = CharField(widget=PasswordInput)
  1008. unbound = UserRegistration()
  1009. bound = UserRegistration({'password': 'foo'})
  1010. self.assertEqual(bound['username'].value(), None)
  1011. self.assertEqual(unbound['username'].value(), 'djangonaut')
  1012. self.assertEqual(bound['password'].value(), 'foo')
  1013. self.assertEqual(unbound['password'].value(), None)
  1014. def test_help_text(self):
  1015. # You can specify descriptive text for a field by using the 'help_text' argument)
  1016. class UserRegistration(Form):
  1017. username = CharField(max_length=10, help_text='e.g., user@example.com')
  1018. password = CharField(widget=PasswordInput, help_text='Choose wisely.')
  1019. p = UserRegistration(auto_id=False)
  1020. self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" /> <span class="helptext">e.g., user@example.com</span></li>
  1021. <li>Password: <input type="password" name="password" /> <span class="helptext">Choose wisely.</span></li>""")
  1022. self.assertEqual(p.as_p(), """<p>Username: <input type="text" name="username" maxlength="10" /> <span class="helptext">e.g., user@example.com</span></p>
  1023. <p>Password: <input type="password" name="password" /> <span class="helptext">Choose wisely.</span></p>""")
  1024. self.assertEqual(p.as_table(), """<tr><th>Username:</th><td><input type="text" name="username" maxlength="10" /><br /><span class="helptext">e.g., user@example.com</span></td></tr>
  1025. <tr><th>Password:</th><td><input type="password" name="password" /><br /><span class="helptext">Choose wisely.</span></td></tr>""")
  1026. # The help text is displayed whether or not data is provided for the form.
  1027. p = UserRegistration({'username': u'foo'}, auto_id=False)
  1028. self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="foo" maxlength="10" /> <span class="helptext">e.g., user@example.com</span></li>
  1029. <li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /> <span class="helptext">Choose wisely.</span></li>""")
  1030. # help_text is not displayed for hidden fields. It can be used for documentation
  1031. # purposes, though.
  1032. class UserRegistration(Form):
  1033. username = CharField(max_length=10, help_text='e.g., user@example.com')
  1034. password = CharField(widget=PasswordInput)
  1035. next = CharField(widget=HiddenInput, initial='/', help_text='Redirect destination')
  1036. p = UserRegistration(auto_id=False)
  1037. self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" /> <span class="helptext">e.g., user@example.com</span></li>
  1038. <li>Password: <input type="password" name="password" /><input type="hidden" name="next" value="/" /></li>""")
  1039. # Help text can include arbitrary Unicode characters.
  1040. class UserRegistration(Form):
  1041. username = CharField(max_length=10, help_text='Š??Ž?žš?')
  1042. p = UserRegistration(auto_id=False)
  1043. self.assertEqual(p.as_ul(), u'<li>Username: <input type="text" name="username" maxlength="10" /> <span class="helptext">\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111</span></li>')
  1044. def test_subclassing_forms(self):
  1045. # You can subclass a Form to add fields. The resulting form subclass will have
  1046. # all of the fields of the parent Form, plus whichever fields you define in the
  1047. # subclass.
  1048. class Person(Form):
  1049. first_name = CharField()
  1050. last_name = CharField()
  1051. birthday = DateField()
  1052. class Musician(Person):
  1053. instrument = CharField()
  1054. p = Person(auto_id=False)
  1055. self.assertEqual(p.as_ul(), """<li>First name: <input type="text" name="first_name" /></li>
  1056. <li>Last name: <input type="text" name="last_name" /></li>
  1057. <li>Birthday: <input type="text" name="birthday" /></li>""")
  1058. m = Musician(auto_id=False)
  1059. self.assertEqual(m.as_ul(), """<li>First name: <input type="text" name="first_name" /></li>
  1060. <li>Last name: <input type="text" name="last_name" /></li>
  1061. <li>Birthday: <input type="text" name="birthday" /></li>
  1062. <li>Instrument: <input type="text" name="instrument" /></li>""")
  1063. # Yes, you can subclass multiple forms. The fields are added in the order in
  1064. # which the parent classes are listed.
  1065. class Person(Form):
  1066. first_name = CharField()
  1067. last_name = CharField()
  1068. birthday = DateField()
  1069. class Instrument(Form):
  1070. instrument = CharField()
  1071. class Beatle(Person, Instrument):
  1072. haircut_type = CharField()
  1073. b = Beatle(auto_id=False)
  1074. self.assertEqual(b.as_ul(), """<li>First name: <input type="text" name="first_name" /></li>
  1075. <li>Last name: <input type="text" name="last_name" /></li>
  1076. <li>Birthday: <input type="text" name="birthday" /></li>
  1077. <li>Instrument: <input type="text" name="instrument" /></li>
  1078. <li>Haircut type: <input type="text" name="haircut_type" /></li>""")
  1079. def test_forms_with_prefixes(self):
  1080. # Sometimes it's necessary to have multiple forms display on the same HTML page,
  1081. # or multiple copies of the same form. We can accomplish this with form prefixes.
  1082. # Pass the keyword argument 'prefix' to the Form constructor to use this feature.
  1083. # This value will be prepended to each HTML form field name. One way to think
  1084. # about this is "namespaces for HTML forms". Notice that in the data argument,
  1085. # each field's key has the prefix, in this case 'person1', prepended to the
  1086. # actual field name.
  1087. class Person(Form):
  1088. first_name = CharField()
  1089. last_name = CharField()
  1090. birthday = DateField()
  1091. data = {
  1092. 'person1-first_name': u'John',
  1093. 'person1-last_name': u'Lennon',
  1094. 'person1-birthday': u'1940-10-9'
  1095. }
  1096. p = Person(data, prefix='person1')
  1097. self.assertEqual(p.as_ul(), """<li><label for="id_person1-first_name">First name:</label> <input type="text" name="person1-first_name" value="John" id="id_person1-first_name" /></li>
  1098. <li><label for="id_person1-last_name">Last name:</label> <input type="text" name="person1-last_name" value="Lennon" id="id_person1-last_name" /></li>
  1099. <li><label for="id_person1-birthday">Birthday:</label> <input type="text" name="person1-birthday" value="1940-10-9" id="id_person1-birthday" /></li>""")
  1100. self.assertEqual(str(p['first_name']), '<input type="text" name="person1-first_name" value="John" id="id_person1-first_name" />')
  1101. self.assertEqual(str(p['last_name']), '<input type="text" name="person1-last_name" value="Lennon" id="id_person1-last_name" />')
  1102. self.assertEqual(str(p['birthday']), '<input type="text" name="person1-birthday" value="1940-10-9" id="id_person1-birthday" />')
  1103. self.assertEqual(p.errors, {})
  1104. self.assertTrue(p.is_valid())
  1105. self.assertEqual(p.cleaned_data['first_name'], u'John')
  1106. self.assertEqual(p.cleaned_data['last_name'], u'Lennon')
  1107. self.assertEqual(p.cleaned_data['birthday'], datetime.date(1940, 10, 9))
  1108. # Let's try submitting some bad data to make sure form.errors and field.errors
  1109. # work as expected.
  1110. data = {
  1111. 'person1-first_name': u'',
  1112. 'person1-last_name': u'',
  1113. 'person1-birthday': u''
  1114. }
  1115. p = Person(data, prefix='person1')
  1116. self.assertEqual(p.errors['first_name'], [u'This field is required.'])
  1117. self.assertEqual(p.errors['last_name'], [u'This field is required.'])
  1118. self.assertEqual(p.errors['birthday'], [u'This field is required.'])
  1119. self.assertEqual(p['first_name'].errors, [u'This field is required.'])
  1120. try:
  1121. p['person1-first_name'].errors
  1122. self.fail('Attempts to access non-existent fields should fail.')
  1123. except KeyError:
  1124. pass
  1125. # In this example, the data doesn't have a prefix, but the form requires it, so
  1126. # the form doesn't "see" the fields.
  1127. data = {
  1128. 'first_name': u'John',
  1129. 'last_name': u'Lennon',
  1130. 'birthday': u'1940-10-9'
  1131. }
  1132. p = Person(data, prefix='person1')
  1133. self.assertEqual(p.errors['first_name'], [u'This field is required.'])
  1134. self.assertEqual(p.errors['last_name'], [u'This field is required.'])
  1135. self.assertEqual(p.errors['birthday'], [u'This field is required.'])
  1136. # With prefixes, a single data dictionary can hold data for multiple instances
  1137. # of the same form.
  1138. data = {
  1139. 'person1-first_name': u'John',
  1140. 'person1-last_name': u'Lennon',
  1141. 'person1-birthday': u'1940-10-9',
  1142. 'person2-first_name': u'Jim',
  1143. 'person2-last_name': u'Morrison',
  1144. 'person2-birthday': u'1943-12-8'
  1145. }
  1146. p1 = Person(data, prefix='person1')
  1147. self.assertTrue(p1.is_valid())
  1148. self.assertEqual(p1.cleaned_data['first_name'], u'John')
  1149. self.assertEqual(p1.cleaned_data['last_name'], u'Lennon')
  1150. self.assertEqual(p1.cleaned_data['birthday'], datetime.date(1940, 10, 9))
  1151. p2 = Person(data, prefix='person2')
  1152. self.assertTrue(p2.is_valid())
  1153. self.assertEqual(p2.cleaned_data['first_name'], u'Jim')
  1154. self.assertEqual(p2.cleaned_data['last_name'], u'Morrison')
  1155. self.assertEqual(p2.cleaned_data['birthday'], datetime.date(1943, 12, 8))
  1156. # By default, forms append a hyphen between the prefix and the field name, but a
  1157. # form can alter that behavior by implementing the add_prefix() method. This
  1158. # method takes a field name and returns the prefixed field, according to
  1159. # self.prefix.
  1160. class Person(Form):
  1161. first_name = CharField()
  1162. last_name = CharField()
  1163. birthday = DateField()
  1164. def add_prefix(self, field_name):
  1165. return self.prefix and '%s-prefix-%s' % (self.prefix, field_name) or field_name
  1166. p = Person(prefix='foo')
  1167. self.assertEqual(p.as_ul(), """<li><label for="id_foo-prefix-first_name">First name:</label> <input type="text" name="foo-prefix-first_name" id="id_foo-prefix-first_name" /></li>
  1168. <li><label for="id_foo-prefix-last_name">Last name:</label> <input type="text" name="foo-prefix-last_name" id="id_foo-prefix-last_name" /></li>
  1169. <li><label for="id_foo-prefix-birthday">Birthday:</label> <input type="text" name="foo-prefix-birthday" id="id_foo-prefix-birthday" /></li>""")
  1170. data = {
  1171. 'foo-prefix-first_name': u'John',
  1172. 'foo-prefix-last_name': u'Lennon',
  1173. 'foo-prefix-birthday': u'1940-10-9'
  1174. }
  1175. p = Person(data, prefix='foo')
  1176. self.assertTrue(p.is_valid())
  1177. self.assertEqual(p.cleaned_data['first_name'], u'John')
  1178. self.assertEqual(p.cleaned_data['last_name'], u'Lennon')
  1179. self.assertEqual(p.cleaned_data['birthday'], datetime.date(1940, 10, 9))
  1180. def test_forms_with_null_boolean(self):
  1181. # NullBooleanField is a bit of a special case because its presentation (widget)
  1182. # is different than its data. This is handled transparently, though.
  1183. class Person(Form):
  1184. name = CharField()
  1185. is_cool = NullBooleanField()
  1186. p = Person({'name': u'Joe'}, auto_id=False)
  1187. self.assertEqual(str(p['is_cool']), """<select name="is_cool">
  1188. <option value="1" selected="selected">Unknown</option>
  1189. <option value="2">Yes</option>
  1190. <option value="3">No</option>
  1191. </select>""")
  1192. p = Person({'name': u'Joe', 'is_cool': u'1'}, auto_id=False)
  1193. self.assertEqual(str(p['is_cool']), """<select name="is_cool">
  1194. <option value="1" selected="selected">Unknown</option>
  1195. <option value="2">Yes</option>
  1196. <option value="3">No</option>
  1197. </select>""")
  1198. p = Person({'name': u'Joe', 'is_cool': u'2'}, auto_id=False)
  1199. self.assertEqual(str(p['is_cool']), """<select name="is_cool">
  1200. <option value="1">Unknown</option>
  1201. <option value="2" selected="selected">Yes</option>
  1202. <option value="3">No</option>
  1203. </select>""")
  1204. p = Person({'name': u'Joe', 'is_cool': u'3'}, auto_id=False)
  1205. self.assertEqual(str(p['is_cool']), """<select name="is_cool">
  1206. <option value="1">Unknown</option>
  1207. <option value="2">Yes</option>
  1208. <option value="3" selected="selected">No</option>
  1209. </select>""")
  1210. p = Person({'name': u'Joe', 'is_cool': True}, auto_id=False)
  1211. self.assertEqual(str(p['is_cool']), """<select name="is_cool">
  1212. <option value="1">Unknown</option>
  1213. <option value="2" selected="selected">Yes</option>
  1214. <option value="3">No</option>
  1215. </select>""")
  1216. p = Person({'name': u'Joe', 'is_cool': False}, auto_id=False)
  1217. self.assertEqual(str(p['is_cool']), """<select name="is_cool">
  1218. <option value="1">Unknown</option>
  1219. <option value="2">Yes</option>
  1220. <option value="3" selected="selected">No</option>
  1221. </select>""")
  1222. def test_forms_with_file_fields(self):
  1223. # FileFields are a special case because they take their data from the request.FILES,
  1224. # not request.POST.
  1225. class FileForm(Form):
  1226. file1 = FileField()
  1227. f = FileForm(auto_id=False)
  1228. self.assertEqual(f.as_table(), '<tr><th>File1:</th><td><input type="file" name="file1" /></td></tr>')
  1229. f = FileForm(data={}, files={}, auto_id=False)
  1230. self.assertEqual(f.as_table(), '<tr><th>File1:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="file" name="file1" /></td></tr>')
  1231. f = FileForm(data={}, files={'file1': SimpleUploadedFile('name', '')}, auto_id=False)
  1232. self.assertEqual(f.as_table(), '<tr><th>File1:</th><td><ul class="errorlist"><li>The submitted file is empty.</li></ul><input type="file" name="file1" /></td></tr>')
  1233. f = FileForm(data={}, files={'file1': 'something that is not a file'}, auto_id=False)
  1234. self.assertEqual(f.as_table(), '<tr><th>File1:</th><td><ul class="errorlist"><li>No file was submitted. Check the encoding type on the form.</li></ul><input type="file" name="file1" /></td></tr>')
  1235. f = FileForm(data={}, files={'file1': SimpleUploadedFile('name', 'some content')}, auto_id=False)
  1236. self.assertEqual(f.as_table(), '<tr><th>File1:</th><td><input type="file" name="file1" /></td></tr>')
  1237. self.assertTrue(f.is_valid())
  1238. f = FileForm(data={}, files={'file1': SimpleUploadedFile('?????????.txt', '???? ??????? ???? ??? ????????? ?? ??? ?')}, auto_id=False)
  1239. self.assertEqual(f.as_table(), '<tr><th>File1:</th><td><input type="file" name="file1" /></td></tr>')
  1240. def test_basic_processing_in_view(self):
  1241. class UserRegistration(Form):
  1242. username = CharField(max_length=10)
  1243. password1 = CharField(widget=PasswordInput)
  1244. password2 = CharField(widget=PasswordInput)
  1245. def clean(self):
  1246. if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']:
  1247. raise ValidationError(u'Please make sure your passwords match.')
  1248. return self.cleaned_data
  1249. def my_function(method, post_data):
  1250. if method == 'POST':
  1251. form = UserRegistration(post_data, auto_id=False)
  1252. else:
  1253. form = UserRegistration(auto_id=False)
  1254. if form.is_valid():
  1255. return 'VALID: %r' % form.cleaned_data
  1256. t = Template('<form action="" method="post">\n<table>\n{{ form }}\n</table>\n<input type="submit" />\n</form>')
  1257. return t.render(Context({'form': form}))
  1258. # Case 1: GET (an empty form, with no errors).)
  1259. self.assertEqual(my_function('GET', {}), """<form action="" method="post">
  1260. <table>
  1261. <tr><th>Username:</th><td><input type="text" name="username" maxlength="10" /></td></tr>
  1262. <tr><th>Password1:</th><td><input type="password" name="password1" /></td></tr>
  1263. <tr><th>Password2:</th><td><input type="password" name="password2" /></td></tr>
  1264. </table>
  1265. <input type="submit" />
  1266. </form>""")
  1267. # Case 2: POST with erroneous data (a redisplayed form, with errors).)
  1268. self.assertEqual(my_function('POST', {'username': 'this-is-a-long-username', 'password1': 'foo', 'password2': 'bar'}), """<form action="" method="post">
  1269. <table>
  1270. <tr><td colspan="2"><ul class="errorlist"><li>Please make sure your passwords match.</li></ul></td></tr>
  1271. <tr><th>Username:</th><td><ul class="errorlist"><li>Ensure this value has at most 10 characters (it has 23).</li></ul><input type="text" name="username" value="this-is-a-long-username" maxlength="10" /></td></tr>
  1272. <tr><th>Password1:</th><td><input type="password" name="password1" /></td></tr>
  1273. <tr><th>Password2:</th><td><input type="password" name="password2" /></td></tr>
  1274. </table>
  1275. <input type="submit" />
  1276. </form>""")
  1277. # Case 3: POST with valid data (the success message).)
  1278. self.assertEqual(my_function('POST', {'username': 'adrian', 'password1': 'secret', 'password2': 'secret'}), "VALID: {'username': u'adrian', 'password1': u'secret', 'password2': u'secret'}")
  1279. def test_templates_with_forms(self):
  1280. class UserRegistration(Form):
  1281. username = CharField(max_length=10, help_text="Good luck picking a username that doesn't already exist.")
  1282. password1 = CharField(widget=PasswordInput)
  1283. password2 = CharField(widget=PasswordInput)
  1284. def clean(self):
  1285. if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']:
  1286. raise ValidationError(u'Please make sure your passwords match.')
  1287. return self.cleaned_data
  1288. # You have full flexibility in displaying form fields in a template. Just pass a
  1289. # Form instance to the template, and use "dot" access to refer to individual
  1290. # fields. Note, however, that this flexibility comes with the responsibility of
  1291. # displaying all the errors, including any that might not be associated with a
  1292. # particular field.
  1293. t = Template('''<form action="">
  1294. {{ form.username.errors.as_ul }}<p><label>Your username: {{ form.username }}</label></p>
  1295. {{ form.password1.errors.as_ul }}<p><label>Password: {{ form.password1 }}</label></p>
  1296. {{ form.password2.errors.as_ul }}<p><label>Password (again): {{ form.password2 }}</label></p>
  1297. <input type="submit" />
  1298. </form>''')
  1299. self.assertEqual(t.render(Context({'form': UserRegistration(auto_id=False)})), """<form action="">
  1300. <p><label>Your username: <input type="text" name="username" maxlength="10" /></label></p>
  1301. <p><label>Password: <input type="password" name="password1" /></label></p>
  1302. <p><label>Password (again): <input type="password" name="password2" /></label></p>
  1303. <input type="submit" />
  1304. </form>""")
  1305. self.assertEqual(t.render(Context({'form': UserRegistration({'username': 'django'}, auto_id=False)})), """<form action="">
  1306. <p><label>Your username: <input type="text" name="username" value="django" maxlength="10" /></label></p>
  1307. <ul class="errorlist"><li>This field is required.</li></ul><p><label>Password: <input type="password" name="password1" /></label></p>
  1308. <ul class="errorlist"><li>This field is required.</li></ul><p><label>Password (again): <input type="password" name="password2" /></label></p>
  1309. <input type="submit" />
  1310. </form>""")
  1311. # Use form.[field].label to output a field's label. You can specify the label for
  1312. # a field by using the 'label' argument to a Field class. If you don't specify
  1313. # 'label', Django will use the field name with underscores converted to spaces,
  1314. # and the initial letter capitalized.
  1315. t = Template('''<form action="">
  1316. <p><label>{{ form.username.label }}: {{ form.username }}</label></p>
  1317. <p><label>{{ form.password1.label }}: {{ form.password1 }}</label></p>
  1318. <p><label>{{ form.password2.label }}: {{ form.password2 }}</label></p>
  1319. <input type="submit" />
  1320. </form>''')
  1321. self.assertEqual(t.render(Context({'form': UserRegistration(auto_id=False)})), """<form action="">
  1322. <p><label>Username: <input type="text" name="username" maxlength="10" /></label></p>
  1323. <p><label>Password1: <input type="password" name="password1" /></label></p>
  1324. <p><label>Password2: <input type="password" name="password2" /></label></p>
  1325. <input type="submit" />
  1326. </form>""")
  1327. # User form.[field].label_tag to output a field's label with a <label> tag
  1328. # wrapped around it, but *only* if the given field has an "id" attribute.
  1329. # Recall from above that passing the "auto_id" argument to a Form gives each
  1330. # field an "id" attribute.
  1331. t = Template('''<form action="">
  1332. <p>{{ form.username.label_tag }}: {{ form.username }}</p>
  1333. <p>{{ form.password1.label_tag }}: {{ form.password1 }}</p>
  1334. <p>{{ form.password2.label_tag }}: {{ form.password2 }}</p>
  1335. <input type="submit" />
  1336. </form>''')
  1337. self.assertEqual(t.render(Context({'form': UserRegistration(auto_id=False)})), """<form action="">
  1338. <p>Username: <input type="text" name="username" maxlength="10" /></p>
  1339. <p>Password1: <input type="password" name="password1" /></p>
  1340. <p>Password2: <input type="password" name="password2" /></p>
  1341. <input type="submit" />
  1342. </form>""")
  1343. self.assertEqual(t.render(Context({'form': UserRegistration(auto_id='id_%s')})), """<form action="">
  1344. <p><label for="id_username">Username</label>: <input id="id_username" type="text" name="username" maxlength="10" /></p>
  1345. <p><label for="id_password1">Password1</label>: <input type="password" name="password1" id="id_password1" /></p>
  1346. <p><label for="id_password2">Password2</label>: <input type="password" name="password2" id="id_password2" /></p>
  1347. <input type="submit" />
  1348. </form>""")
  1349. # User form.[field].help_text to output a field's help text. If the given field
  1350. # does not have help text, nothing will be output.
  1351. t = Template('''<form action="">
  1352. <p>{{ form.username.label_tag }}: {{ form.username }}<br />{{ form.username.help_text }}</p>
  1353. <p>{{ form.password1.label_tag }}: {{ form.password1 }}</p>
  1354. <p>{{ form.password2.label_tag }}: {{ form.password2 }}</p>
  1355. <input type="submit" />
  1356. </form>''')
  1357. self.assertEqual(t.render(Context({'form': UserRegistration(auto_id=False)})), """<form action="">
  1358. <p>Username: <input type="text" name="username" maxlength="10" /><br />Good luck picking a username that doesn&#39;t already exist.</p>
  1359. <p>Password1: <input type="password" name="password1" /></p>
  1360. <p>Password2: <input type="password" name="password2" /></p>
  1361. <input type="submit" />
  1362. </form>""")
  1363. self.assertEqual(Template('{{ form.password1.help_text }}').render(Context({'form': UserRegistration(auto_id=False)})), u'')
  1364. # The label_tag() method takes an optional attrs argument: a dictionary of HTML
  1365. # attributes to add to the <label> tag.
  1366. f = UserRegistration(auto_id='id_%s')
  1367. form_output = []
  1368. for bf in f:
  1369. form_output.append(bf.label_tag(attrs={'class': 'pretty'}))
  1370. self.assertEqual(form_output, [
  1371. '<label for="id_username" class="pretty">Username</label>',
  1372. '<label for="id_password1" class="pretty">Password1</label>',
  1373. '<label for="id_password2" class="pretty">Password2</label>',
  1374. ])
  1375. # To display the errors that aren't associated with a particular field -- e.g.,
  1376. # the errors caused by Form.clean() -- use {{ form.non_field_errors }} in the
  1377. # template. If used on its own, it is displayed as a <ul> (or an empty string, if
  1378. # the list of errors is empty). You can also use it in {% if %} statements.
  1379. t = Template('''<form action="">
  1380. {{ form.username.errors.as_ul }}<p><label>Your username: {{ form.username }}</label></p>
  1381. {{ form.password1.errors.as_ul }}<p><label>Password: {{ form.password1 }}</label></p>
  1382. {{ form.password2.errors.as_ul }}<p><label>Password (again): {{ form.password2 }}</label></p>
  1383. <input type="submit" />
  1384. </form>''')
  1385. self.assertEqual(t.render(Context({'form': UserRegistration({'username': 'django', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)})), """<form action="">
  1386. <p><label>Your username: <input type="text" name="username" value="django" maxlength="10" /></label></p>
  1387. <p><label>Password: <input type="password" name="password1" /></label></p>
  1388. <p><label>Password (again): <input type="password" name="password2" /></label></p>
  1389. <input type="submit" />
  1390. </form>""")
  1391. t = Template('''<form action="">
  1392. {{ form.non_field_errors }}
  1393. {{ form.username.errors.as_ul }}<p><label>Your username: {{ form.username }}</label></p>
  1394. {{ form.password1.errors.as_ul }}<p><label>Password: {{ form.password1 }}</label></p>
  1395. {{ form.password2.errors.as_ul }}<p><label>Password (again): {{ form.password2 }}</label></p>
  1396. <input type="submit" />
  1397. </form>''')
  1398. self.assertEqual(t.render(Context({'form': UserRegistration({'username': 'django', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)})), """<form action="">
  1399. <ul class="errorlist"><li>Please make sure your passwords match.</li></ul>
  1400. <p><label>Your username: <input type="text" name="username" value="django" maxlength="10" /></label></p>
  1401. <p><label>Password: <input type="password" name="password1" /></label></p>
  1402. <p><label>Password (again): <input type="password" name="password2" /></label></p>
  1403. <input type="submit" />
  1404. </form>""")
  1405. def test_empty_permitted(self):
  1406. # Sometimes (pretty much in formsets) we want to allow a form to pass validation
  1407. # if it is completely empty. We can accomplish this by using the empty_permitted
  1408. # agrument to a form constructor.
  1409. class SongForm(Form):
  1410. artist = CharField()
  1411. name = CharField()
  1412. # First let's show what happens id empty_permitted=False (the default):
  1413. data = {'artist': '', 'song': ''}
  1414. form = SongForm(data, empty_permitted=False)
  1415. self.assertFalse(form.is_valid())
  1416. self.assertEqual(form.errors, {'name': [u'This field is required.'], 'artist': [u'This field is required.']})
  1417. try:
  1418. form.cleaned_data
  1419. self.fail('Attempts to access cleaned_data when validation fails should fail.')
  1420. except AttributeError:
  1421. pass
  1422. # Now let's show what happens when empty_permitted=True and the form is empty.
  1423. form = SongForm(data, empty_permitted=True)
  1424. self.assertTrue(form.is_valid())
  1425. self.assertEqual(form.errors, {})
  1426. self.assertEqual(form.cleaned_data, {})
  1427. # But if we fill in data for one of the fields, the form is no longer empty and
  1428. # the whole thing must pass validation.
  1429. data = {'artist': 'The Doors', 'song': ''}
  1430. form = SongForm(data, empty_permitted=False)
  1431. self.assertFalse(form.is_valid())
  1432. self.assertEqual(form.errors, {'name': [u'This field is required.']})
  1433. try:
  1434. form.cleaned_data
  1435. self.fail('Attempts to access cleaned_data when validation fails should fail.')
  1436. except AttributeError:
  1437. pass
  1438. # If a field is not given in the data then None is returned for its data. Lets
  1439. # make sure that when checking for empty_permitted that None is treated
  1440. # accordingly.
  1441. data = {'artist': None, 'song': ''}
  1442. form = SongForm(data, empty_permitted=True)
  1443. self.assertTrue(form.is_valid())
  1444. # However, we *really* need to be sure we are checking for None as any data in
  1445. # initial that returns False on a boolean call needs to be treated literally.
  1446. class PriceForm(Form):
  1447. amount = FloatField()
  1448. qty = IntegerField()
  1449. data = {'amount': '0.0', 'qty': ''}
  1450. form = PriceForm(data, initial={'amount': 0.0}, empty_permitted=True)
  1451. self.assertTrue(form.is_valid())
  1452. def test_extracting_hidden_and_visible(self):
  1453. class SongForm(Form):
  1454. token = CharField(widget=HiddenInput)
  1455. artist = CharField()
  1456. name = CharField()
  1457. form = SongForm()
  1458. self.assertEqual([f.name for f in form.hidden_fields()], ['token'])
  1459. self.assertEqual([f.name for f in form.visible_fields()], ['artist', 'name'])
  1460. def test_hidden_initial_gets_id(self):
  1461. class MyForm(Form):
  1462. field1 = CharField(max_length=50, show_hidden_initial=True)
  1463. self.assertEqual(MyForm().as_table(), '<tr><th><label for="id_field1">Field1:</label></th><td><input id="id_field1" type="text" name="field1" maxlength="50" /><input type="hidden" name="initial-field1" id="initial-id_field1" /></td></tr>')
  1464. def test_error_html_required_html_classes(self):
  1465. class Person(Form):
  1466. name = CharField()
  1467. is_cool = NullBooleanField()
  1468. email = EmailField(required=False)
  1469. age = IntegerField()
  1470. p = Person({})
  1471. p.error_css_class = 'error'
  1472. p.required_css_class = 'required'
  1473. self.assertEqual(p.as_ul(), """<li class="required error"><ul class="errorlist"><li>This field is required.</li></ul><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" /></li>
  1474. <li class="required"><label for="id_is_cool">Is cool:</label> <select name="is_cool" id="id_is_cool">
  1475. <option value="1" selected="selected">Unknown</option>
  1476. <option value="2">Yes</option>
  1477. <option value="3">No</option>
  1478. </select></li>
  1479. <li><label for="id_email">Email:</label> <input type="text" name="email" id="id_email" /></li>
  1480. <li class="required error"><ul class="errorlist"><li>This field is required.</li></ul><label for="id_age">Age:</label> <input type="text" name="age" id="id_age" /></li>""")
  1481. self.assertEqual(p.as_p(), """<ul class="errorlist"><li>This field is required.</li></ul>
  1482. <p class="required error"><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" /></p>
  1483. <p class="required"><label for="id_is_cool">Is cool:</label> <select name="is_cool" id="id_is_cool">
  1484. <option value="1" selected="selected">Unknown</option>
  1485. <option value="2">Yes</option>
  1486. <option value="3">No</option>
  1487. </select></p>
  1488. <p><label for="id_email">Email:</label> <input type="text" name="email" id="id_email" /></p>
  1489. <ul class="errorlist"><li>This field is required.</li></ul>
  1490. <p class="required error"><label for="id_age">Age:</label> <input type="text" name="age" id="id_age" /></p>""")
  1491. self.assertEqual(p.as_table(), """<tr class="required error"><th><label for="id_name">Name:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="name" id="id_name" /></td></tr>
  1492. <tr class="required"><th><label for="id_is_cool">Is cool:</label></th><td><select name="is_cool" id="id_is_cool">
  1493. <option value="1" selected="selected">Unknown</option>
  1494. <option value="2">Yes</option>
  1495. <option value="3">No</option>
  1496. </select></td></tr>
  1497. <tr><th><label for="id_email">Email:</label></th><td><input type="text" name="email" id="id_email" /></td></tr>
  1498. <tr class="required error"><th><label for="id_age">Age:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="age" id="id_age" /></td></tr>""")
  1499. def test_label_split_datetime_not_displayed(self):
  1500. class EventForm(Form):
  1501. happened_at = SplitDateTimeField(widget=widgets.SplitHiddenDateTimeWidget)
  1502. form = EventForm()
  1503. self.assertEqual(form.as_ul(), u'<input type="hidden" name="happened_at_0" id="id_happened_at_0" /><input type="hidden" name="happened_at_1" id="id_happened_at_1" />')