forms.py 103 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755
  1. # -*- coding: utf-8 -*-
  2. import datetime
  3. from django.core.files.uploadedfile import SimpleUploadedFile
  4. from django.forms import *
  5. from django.http import QueryDict
  6. from django.template import Template, Context
  7. from django.utils.datastructures import MultiValueDict, MergeDict
  8. from django.utils.safestring import mark_safe
  9. from django.utils.unittest import TestCase
  10. class Person(Form):
  11. first_name = CharField()
  12. last_name = CharField()
  13. birthday = DateField()
  14. class PersonNew(Form):
  15. first_name = CharField(widget=TextInput(attrs={'id': 'first_name_id'}))
  16. last_name = CharField()
  17. birthday = DateField()
  18. class FormsTestCase(TestCase):
  19. # A Form is a collection of Fields. It knows how to validate a set of data and it
  20. # knows how to render itself in a couple of default ways (e.g., an HTML table).
  21. # You can pass it data in __init__(), as a dictionary.
  22. def test_form(self):
  23. # Pass a dictionary to a Form's __init__().
  24. p = Person({'first_name': u'John', 'last_name': u'Lennon', 'birthday': u'1940-10-9'})
  25. self.assertTrue(p.is_bound)
  26. self.assertEqual(p.errors, {})
  27. self.assertTrue(p.is_valid())
  28. self.assertEqual(p.errors.as_ul(), u'')
  29. self.assertEqual(p.errors.as_text(), u'')
  30. self.assertEqual(p.cleaned_data["first_name"], u'John')
  31. self.assertEqual(p.cleaned_data["last_name"], u'Lennon')
  32. self.assertEqual(p.cleaned_data["birthday"], datetime.date(1940, 10, 9))
  33. self.assertEqual(str(p['first_name']), '<input type="text" name="first_name" value="John" id="id_first_name" />')
  34. self.assertEqual(str(p['last_name']), '<input type="text" name="last_name" value="Lennon" id="id_last_name" />')
  35. self.assertEqual(str(p['birthday']), '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" />')
  36. try:
  37. p['nonexistentfield']
  38. self.fail('Attempts to access non-existent fields should fail.')
  39. except KeyError:
  40. pass
  41. form_output = []
  42. for boundfield in p:
  43. form_output.append(str(boundfield))
  44. self.assertEqual('\n'.join(form_output), """<input type="text" name="first_name" value="John" id="id_first_name" />
  45. <input type="text" name="last_name" value="Lennon" id="id_last_name" />
  46. <input type="text" name="birthday" value="1940-10-9" id="id_birthday" />""")
  47. form_output = []
  48. for boundfield in p:
  49. form_output.append([boundfield.label, boundfield.data])
  50. self.assertEqual(form_output, [
  51. ['First name', u'John'],
  52. ['Last name', u'Lennon'],
  53. ['Birthday', u'1940-10-9']
  54. ])
  55. 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>
  56. <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>
  57. <tr><th><label for="id_birthday">Birthday:</label></th><td><input type="text" name="birthday" value="1940-10-9" id="id_birthday" /></td></tr>""")
  58. def test_empty_dict(self):
  59. # Empty dictionaries are valid, too.
  60. p = Person({})
  61. self.assertTrue(p.is_bound)
  62. self.assertEqual(p.errors['first_name'], [u'This field is required.'])
  63. self.assertEqual(p.errors['last_name'], [u'This field is required.'])
  64. self.assertEqual(p.errors['birthday'], [u'This field is required.'])
  65. self.assertFalse(p.is_valid())
  66. try:
  67. p.cleaned_data
  68. self.fail('Attempts to access cleaned_data when validation fails should fail.')
  69. except AttributeError:
  70. pass
  71. 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>
  72. <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>
  73. <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>""")
  74. 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>
  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_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>
  78. <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>
  79. <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>""")
  80. self.assertEqual(p.as_p(), """<ul class="errorlist"><li>This field is required.</li></ul>
  81. <p><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" /></p>
  82. <ul class="errorlist"><li>This field is required.</li></ul>
  83. <p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></p>
  84. <ul class="errorlist"><li>This field is required.</li></ul>
  85. <p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /></p>""")
  86. def test_unbound_form(self):
  87. # If you don't pass any values to the Form's __init__(), or if you pass None,
  88. # the Form will be considered unbound and won't do any validation. Form.errors
  89. # will be an empty dictionary *but* Form.is_valid() will return False.
  90. p = Person()
  91. self.assertFalse(p.is_bound)
  92. self.assertEqual(p.errors, {})
  93. self.assertFalse(p.is_valid())
  94. try:
  95. p.cleaned_data
  96. self.fail('Attempts to access cleaned_data when validation fails should fail.')
  97. except AttributeError:
  98. pass
  99. 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>
  100. <tr><th><label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" id="id_last_name" /></td></tr>
  101. <tr><th><label for="id_birthday">Birthday:</label></th><td><input type="text" name="birthday" id="id_birthday" /></td></tr>""")
  102. 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>
  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_ul(), """<li><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" /></li>
  106. <li><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></li>
  107. <li><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /></li>""")
  108. 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>
  109. <p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></p>
  110. <p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /></p>""")
  111. def test_unicode_values(self):
  112. # Unicode values are handled properly.
  113. p = Person({'first_name': u'John', 'last_name': u'\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111', 'birthday': '1940-10-9'})
  114. 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>')
  115. 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>')
  116. 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>')
  117. p = Person({'last_name': u'Lennon'})
  118. self.assertEqual(p.errors['first_name'], [u'This field is required.'])
  119. self.assertEqual(p.errors['birthday'], [u'This field is required.'])
  120. self.assertFalse(p.is_valid())
  121. 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>')
  122. self.assertEqual(p.errors.as_text(), """* first_name
  123. * This field is required.
  124. * birthday
  125. * This field is required.""")
  126. try:
  127. p.cleaned_data
  128. self.fail('Attempts to access cleaned_data when validation fails should fail.')
  129. except AttributeError:
  130. pass
  131. self.assertEqual(p['first_name'].errors, [u'This field is required.'])
  132. self.assertEqual(p['first_name'].errors.as_ul(), u'<ul class="errorlist"><li>This field is required.</li></ul>')
  133. self.assertEqual(p['first_name'].errors.as_text(), u'* This field is required.')
  134. p = Person()
  135. self.assertEqual(str(p['first_name']), '<input type="text" name="first_name" id="id_first_name" />')
  136. self.assertEqual(str(p['last_name']), '<input type="text" name="last_name" id="id_last_name" />')
  137. self.assertEqual(str(p['birthday']), '<input type="text" name="birthday" id="id_birthday" />')
  138. def test_cleaned_data_only_fields(self):
  139. # cleaned_data will always *only* contain a key for fields defined in the
  140. # Form, even if you pass extra data when you define the Form. In this
  141. # example, we pass a bunch of extra fields to the form constructor,
  142. # but cleaned_data contains only the form's fields.
  143. data = {'first_name': u'John', 'last_name': u'Lennon', 'birthday': u'1940-10-9', 'extra1': 'hello', 'extra2': 'hello'}
  144. p = Person(data)
  145. self.assertTrue(p.is_valid())
  146. self.assertEqual(p.cleaned_data['first_name'], u'John')
  147. self.assertEqual(p.cleaned_data['last_name'], u'Lennon')
  148. self.assertEqual(p.cleaned_data['birthday'], datetime.date(1940, 10, 9))
  149. def test_optional_data(self):
  150. # cleaned_data will include a key and value for *all* fields defined in the Form,
  151. # even if the Form's data didn't include a value for fields that are not
  152. # required. In this example, the data dictionary doesn't include a value for the
  153. # "nick_name" field, but cleaned_data includes it. For CharFields, it's set to the
  154. # empty string.
  155. class OptionalPersonForm(Form):
  156. first_name = CharField()
  157. last_name = CharField()
  158. nick_name = CharField(required=False)
  159. data = {'first_name': u'John', 'last_name': u'Lennon'}
  160. f = OptionalPersonForm(data)
  161. self.assertTrue(f.is_valid())
  162. self.assertEqual(f.cleaned_data['nick_name'], u'')
  163. self.assertEqual(f.cleaned_data['first_name'], u'John')
  164. self.assertEqual(f.cleaned_data['last_name'], u'Lennon')
  165. # For DateFields, it's set to None.
  166. class OptionalPersonForm(Form):
  167. first_name = CharField()
  168. last_name = CharField()
  169. birth_date = DateField(required=False)
  170. data = {'first_name': u'John', 'last_name': u'Lennon'}
  171. f = OptionalPersonForm(data)
  172. self.assertTrue(f.is_valid())
  173. self.assertEqual(f.cleaned_data['birth_date'], None)
  174. self.assertEqual(f.cleaned_data['first_name'], u'John')
  175. self.assertEqual(f.cleaned_data['last_name'], u'Lennon')
  176. def test_auto_id(self):
  177. # "auto_id" tells the Form to add an "id" attribute to each form element.
  178. # If it's a string that contains '%s', Django will use that as a format string
  179. # into which the field's name will be inserted. It will also put a <label> around
  180. # the human-readable labels for a field.
  181. p = Person(auto_id='%s_id')
  182. 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>
  183. <tr><th><label for="last_name_id">Last name:</label></th><td><input type="text" name="last_name" id="last_name_id" /></td></tr>
  184. <tr><th><label for="birthday_id">Birthday:</label></th><td><input type="text" name="birthday" id="birthday_id" /></td></tr>""")
  185. 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>
  186. <li><label for="last_name_id">Last name:</label> <input type="text" name="last_name" id="last_name_id" /></li>
  187. <li><label for="birthday_id">Birthday:</label> <input type="text" name="birthday" id="birthday_id" /></li>""")
  188. 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>
  189. <p><label for="last_name_id">Last name:</label> <input type="text" name="last_name" id="last_name_id" /></p>
  190. <p><label for="birthday_id">Birthday:</label> <input type="text" name="birthday" id="birthday_id" /></p>""")
  191. def test_auto_id_true(self):
  192. # If auto_id is any True value whose str() does not contain '%s', the "id"
  193. # attribute will be the name of the field.
  194. p = Person(auto_id=True)
  195. self.assertEqual(p.as_ul(), """<li><label for="first_name">First name:</label> <input type="text" name="first_name" id="first_name" /></li>
  196. <li><label for="last_name">Last name:</label> <input type="text" name="last_name" id="last_name" /></li>
  197. <li><label for="birthday">Birthday:</label> <input type="text" name="birthday" id="birthday" /></li>""")
  198. def test_auto_id_false(self):
  199. # If auto_id is any False value, an "id" attribute won't be output unless it
  200. # was manually entered.
  201. p = Person(auto_id=False)
  202. self.assertEqual(p.as_ul(), """<li>First name: <input type="text" name="first_name" /></li>
  203. <li>Last name: <input type="text" name="last_name" /></li>
  204. <li>Birthday: <input type="text" name="birthday" /></li>""")
  205. def test_id_on_field(self):
  206. # In this example, auto_id is False, but the "id" attribute for the "first_name"
  207. # field is given. Also note that field gets a <label>, while the others don't.
  208. p = PersonNew(auto_id=False)
  209. 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>
  210. <li>Last name: <input type="text" name="last_name" /></li>
  211. <li>Birthday: <input type="text" name="birthday" /></li>""")
  212. def test_auto_id_on_form_and_field(self):
  213. # If the "id" attribute is specified in the Form and auto_id is True, the "id"
  214. # attribute in the Form gets precedence.
  215. p = PersonNew(auto_id=True)
  216. 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>
  217. <li><label for="last_name">Last name:</label> <input type="text" name="last_name" id="last_name" /></li>
  218. <li><label for="birthday">Birthday:</label> <input type="text" name="birthday" id="birthday" /></li>""")
  219. def test_various_boolean_values(self):
  220. class SignupForm(Form):
  221. email = EmailField()
  222. get_spam = BooleanField()
  223. f = SignupForm(auto_id=False)
  224. self.assertEqual(str(f['email']), '<input type="text" name="email" />')
  225. self.assertEqual(str(f['get_spam']), '<input type="checkbox" name="get_spam" />')
  226. f = SignupForm({'email': 'test@example.com', 'get_spam': True}, auto_id=False)
  227. self.assertEqual(str(f['email']), '<input type="text" name="email" value="test@example.com" />')
  228. self.assertEqual(str(f['get_spam']), '<input checked="checked" type="checkbox" name="get_spam" />')
  229. # 'True' or 'true' should be rendered without a value attribute
  230. f = SignupForm({'email': 'test@example.com', 'get_spam': 'True'}, auto_id=False)
  231. self.assertEqual(str(f['get_spam']), '<input checked="checked" type="checkbox" name="get_spam" />')
  232. f = SignupForm({'email': 'test@example.com', 'get_spam': 'true'}, auto_id=False)
  233. self.assertEqual(str(f['get_spam']), '<input checked="checked" type="checkbox" name="get_spam" />')
  234. # A value of 'False' or 'false' should be rendered unchecked
  235. f = SignupForm({'email': 'test@example.com', 'get_spam': 'False'}, auto_id=False)
  236. self.assertEqual(str(f['get_spam']), '<input type="checkbox" name="get_spam" />')
  237. f = SignupForm({'email': 'test@example.com', 'get_spam': 'false'}, auto_id=False)
  238. self.assertEqual(str(f['get_spam']), '<input type="checkbox" name="get_spam" />')
  239. def test_widget_output(self):
  240. # Any Field can have a Widget class passed to its constructor:
  241. class ContactForm(Form):
  242. subject = CharField()
  243. message = CharField(widget=Textarea)
  244. f = ContactForm(auto_id=False)
  245. self.assertEqual(str(f['subject']), '<input type="text" name="subject" />')
  246. self.assertEqual(str(f['message']), '<textarea rows="10" cols="40" name="message"></textarea>')
  247. # as_textarea(), as_text() and as_hidden() are shortcuts for changing the output
  248. # widget type:
  249. self.assertEqual(f['subject'].as_textarea(), u'<textarea rows="10" cols="40" name="subject"></textarea>')
  250. self.assertEqual(f['message'].as_text(), u'<input type="text" name="message" />')
  251. self.assertEqual(f['message'].as_hidden(), u'<input type="hidden" name="message" />')
  252. # The 'widget' parameter to a Field can also be an instance:
  253. class ContactForm(Form):
  254. subject = CharField()
  255. message = CharField(widget=Textarea(attrs={'rows': 80, 'cols': 20}))
  256. f = ContactForm(auto_id=False)
  257. self.assertEqual(str(f['message']), '<textarea rows="80" cols="20" name="message"></textarea>')
  258. # Instance-level attrs are *not* carried over to as_textarea(), as_text() and
  259. # as_hidden():
  260. self.assertEqual(f['message'].as_text(), u'<input type="text" name="message" />')
  261. f = ContactForm({'subject': 'Hello', 'message': 'I love you.'}, auto_id=False)
  262. self.assertEqual(f['subject'].as_textarea(), u'<textarea rows="10" cols="40" name="subject">Hello</textarea>')
  263. self.assertEqual(f['message'].as_text(), u'<input type="text" name="message" value="I love you." />')
  264. self.assertEqual(f['message'].as_hidden(), u'<input type="hidden" name="message" value="I love you." />')
  265. def test_forms_with_choices(self):
  266. # For a form with a <select>, use ChoiceField:
  267. class FrameworkForm(Form):
  268. name = CharField()
  269. language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')])
  270. f = FrameworkForm(auto_id=False)
  271. self.assertEqual(str(f['language']), """<select name="language">
  272. <option value="P">Python</option>
  273. <option value="J">Java</option>
  274. </select>""")
  275. f = FrameworkForm({'name': 'Django', 'language': 'P'}, auto_id=False)
  276. self.assertEqual(str(f['language']), """<select name="language">
  277. <option value="P" selected="selected">Python</option>
  278. <option value="J">Java</option>
  279. </select>""")
  280. # A subtlety: If one of the choices' value is the empty string and the form is
  281. # unbound, then the <option> for the empty-string choice will get selected="selected".
  282. class FrameworkForm(Form):
  283. name = CharField()
  284. language = ChoiceField(choices=[('', '------'), ('P', 'Python'), ('J', 'Java')])
  285. f = FrameworkForm(auto_id=False)
  286. self.assertEqual(str(f['language']), """<select name="language">
  287. <option value="" selected="selected">------</option>
  288. <option value="P">Python</option>
  289. <option value="J">Java</option>
  290. </select>""")
  291. # You can specify widget attributes in the Widget constructor.
  292. class FrameworkForm(Form):
  293. name = CharField()
  294. language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')], widget=Select(attrs={'class': 'foo'}))
  295. f = FrameworkForm(auto_id=False)
  296. self.assertEqual(str(f['language']), """<select class="foo" name="language">
  297. <option value="P">Python</option>
  298. <option value="J">Java</option>
  299. </select>""")
  300. f = FrameworkForm({'name': 'Django', 'language': 'P'}, auto_id=False)
  301. self.assertEqual(str(f['language']), """<select class="foo" name="language">
  302. <option value="P" selected="selected">Python</option>
  303. <option value="J">Java</option>
  304. </select>""")
  305. # When passing a custom widget instance to ChoiceField, note that setting
  306. # 'choices' on the widget is meaningless. The widget will use the choices
  307. # defined on the Field, not the ones defined on the Widget.
  308. class FrameworkForm(Form):
  309. name = CharField()
  310. language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')], widget=Select(choices=[('R', 'Ruby'), ('P', 'Perl')], attrs={'class': 'foo'}))
  311. f = FrameworkForm(auto_id=False)
  312. self.assertEqual(str(f['language']), """<select class="foo" name="language">
  313. <option value="P">Python</option>
  314. <option value="J">Java</option>
  315. </select>""")
  316. f = FrameworkForm({'name': 'Django', 'language': 'P'}, auto_id=False)
  317. self.assertEqual(str(f['language']), """<select class="foo" name="language">
  318. <option value="P" selected="selected">Python</option>
  319. <option value="J">Java</option>
  320. </select>""")
  321. # You can set a ChoiceField's choices after the fact.
  322. class FrameworkForm(Form):
  323. name = CharField()
  324. language = ChoiceField()
  325. f = FrameworkForm(auto_id=False)
  326. self.assertEqual(str(f['language']), """<select name="language">
  327. </select>""")
  328. f.fields['language'].choices = [('P', 'Python'), ('J', 'Java')]
  329. self.assertEqual(str(f['language']), """<select name="language">
  330. <option value="P">Python</option>
  331. <option value="J">Java</option>
  332. </select>""")
  333. def test_forms_with_radio(self):
  334. # Add widget=RadioSelect to use that widget with a ChoiceField.
  335. class FrameworkForm(Form):
  336. name = CharField()
  337. language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')], widget=RadioSelect)
  338. f = FrameworkForm(auto_id=False)
  339. self.assertEqual(str(f['language']), """<ul>
  340. <li><label><input type="radio" name="language" value="P" /> Python</label></li>
  341. <li><label><input type="radio" name="language" value="J" /> Java</label></li>
  342. </ul>""")
  343. self.assertEqual(f.as_table(), """<tr><th>Name:</th><td><input type="text" name="name" /></td></tr>
  344. <tr><th>Language:</th><td><ul>
  345. <li><label><input type="radio" name="language" value="P" /> Python</label></li>
  346. <li><label><input type="radio" name="language" value="J" /> Java</label></li>
  347. </ul></td></tr>""")
  348. self.assertEqual(f.as_ul(), """<li>Name: <input type="text" name="name" /></li>
  349. <li>Language: <ul>
  350. <li><label><input type="radio" name="language" value="P" /> Python</label></li>
  351. <li><label><input type="radio" name="language" value="J" /> Java</label></li>
  352. </ul></li>""")
  353. # Regarding auto_id and <label>, RadioSelect is a special case. Each radio button
  354. # gets a distinct ID, formed by appending an underscore plus the button's
  355. # zero-based index.
  356. f = FrameworkForm(auto_id='id_%s')
  357. self.assertEqual(str(f['language']), """<ul>
  358. <li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" /> Python</label></li>
  359. <li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" /> Java</label></li>
  360. </ul>""")
  361. # When RadioSelect is used with auto_id, and the whole form is printed using
  362. # either as_table() or as_ul(), the label for the RadioSelect will point to the
  363. # ID of the *first* radio button.
  364. 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>
  365. <tr><th><label for="id_language_0">Language:</label></th><td><ul>
  366. <li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" /> Python</label></li>
  367. <li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" /> Java</label></li>
  368. </ul></td></tr>""")
  369. self.assertEqual(f.as_ul(), """<li><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" /></li>
  370. <li><label for="id_language_0">Language:</label> <ul>
  371. <li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" /> Python</label></li>
  372. <li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" /> Java</label></li>
  373. </ul></li>""")
  374. self.assertEqual(f.as_p(), """<p><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" /></p>
  375. <p><label for="id_language_0">Language:</label> <ul>
  376. <li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" /> Python</label></li>
  377. <li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" /> Java</label></li>
  378. </ul></p>""")
  379. def test_forms_wit_hmultiple_choice(self):
  380. # MultipleChoiceField is a special case, as its data is required to be a list:
  381. class SongForm(Form):
  382. name = CharField()
  383. composers = MultipleChoiceField()
  384. f = SongForm(auto_id=False)
  385. self.assertEqual(str(f['composers']), """<select multiple="multiple" name="composers">
  386. </select>""")
  387. class SongForm(Form):
  388. name = CharField()
  389. composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')])
  390. f = SongForm(auto_id=False)
  391. self.assertEqual(str(f['composers']), """<select multiple="multiple" name="composers">
  392. <option value="J">John Lennon</option>
  393. <option value="P">Paul McCartney</option>
  394. </select>""")
  395. f = SongForm({'name': 'Yesterday', 'composers': ['P']}, auto_id=False)
  396. self.assertEqual(str(f['name']), '<input type="text" name="name" value="Yesterday" />')
  397. self.assertEqual(str(f['composers']), """<select multiple="multiple" name="composers">
  398. <option value="J">John Lennon</option>
  399. <option value="P" selected="selected">Paul McCartney</option>
  400. </select>""")
  401. def test_hidden_data(self):
  402. class SongForm(Form):
  403. name = CharField()
  404. composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')])
  405. # MultipleChoiceField rendered as_hidden() is a special case. Because it can
  406. # have multiple values, its as_hidden() renders multiple <input type="hidden">
  407. # tags.
  408. f = SongForm({'name': 'Yesterday', 'composers': ['P']}, auto_id=False)
  409. self.assertEqual(f['composers'].as_hidden(), '<input type="hidden" name="composers" value="P" />')
  410. f = SongForm({'name': 'From Me To You', 'composers': ['P', 'J']}, auto_id=False)
  411. self.assertEqual(f['composers'].as_hidden(), """<input type="hidden" name="composers" value="P" />
  412. <input type="hidden" name="composers" value="J" />""")
  413. # DateTimeField rendered as_hidden() is special too
  414. class MessageForm(Form):
  415. when = SplitDateTimeField()
  416. f = MessageForm({'when_0': '1992-01-01', 'when_1': '01:01'})
  417. self.assertTrue(f.is_valid())
  418. 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" />')
  419. 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" />')
  420. def test_mulitple_choice_checkbox(self):
  421. # MultipleChoiceField can also be used with the CheckboxSelectMultiple widget.
  422. class SongForm(Form):
  423. name = CharField()
  424. composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=CheckboxSelectMultiple)
  425. f = SongForm(auto_id=False)
  426. self.assertEqual(str(f['composers']), """<ul>
  427. <li><label><input type="checkbox" name="composers" value="J" /> John Lennon</label></li>
  428. <li><label><input type="checkbox" name="composers" value="P" /> Paul McCartney</label></li>
  429. </ul>""")
  430. f = SongForm({'composers': ['J']}, auto_id=False)
  431. self.assertEqual(str(f['composers']), """<ul>
  432. <li><label><input checked="checked" type="checkbox" name="composers" value="J" /> John Lennon</label></li>
  433. <li><label><input type="checkbox" name="composers" value="P" /> Paul McCartney</label></li>
  434. </ul>""")
  435. f = SongForm({'composers': ['J', 'P']}, auto_id=False)
  436. self.assertEqual(str(f['composers']), """<ul>
  437. <li><label><input checked="checked" type="checkbox" name="composers" value="J" /> John Lennon</label></li>
  438. <li><label><input checked="checked" type="checkbox" name="composers" value="P" /> Paul McCartney</label></li>
  439. </ul>""")
  440. def test_checkbox_auto_id(self):
  441. # Regarding auto_id, CheckboxSelectMultiple is a special case. Each checkbox
  442. # gets a distinct ID, formed by appending an underscore plus the checkbox's
  443. # zero-based index.
  444. class SongForm(Form):
  445. name = CharField()
  446. composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=CheckboxSelectMultiple)
  447. f = SongForm(auto_id='%s_id')
  448. self.assertEqual(str(f['composers']), """<ul>
  449. <li><label for="composers_id_0"><input type="checkbox" name="composers" value="J" id="composers_id_0" /> John Lennon</label></li>
  450. <li><label for="composers_id_1"><input type="checkbox" name="composers" value="P" id="composers_id_1" /> Paul McCartney</label></li>
  451. </ul>""")
  452. def test_multiple_choice_list_data(self):
  453. # Data for a MultipleChoiceField should be a list. QueryDict, MultiValueDict and
  454. # MergeDict (when created as a merge of MultiValueDicts) conveniently work with
  455. # this.
  456. class SongForm(Form):
  457. name = CharField()
  458. composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=CheckboxSelectMultiple)
  459. data = {'name': 'Yesterday', 'composers': ['J', 'P']}
  460. f = SongForm(data)
  461. self.assertEqual(f.errors, {})
  462. data = QueryDict('name=Yesterday&composers=J&composers=P')
  463. f = SongForm(data)
  464. self.assertEqual(f.errors, {})
  465. data = MultiValueDict(dict(name=['Yesterday'], composers=['J', 'P']))
  466. f = SongForm(data)
  467. self.assertEqual(f.errors, {})
  468. data = MergeDict(MultiValueDict(dict(name=['Yesterday'], composers=['J', 'P'])))
  469. f = SongForm(data)
  470. self.assertEqual(f.errors, {})
  471. def test_multiple_hidden(self):
  472. class SongForm(Form):
  473. name = CharField()
  474. composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=CheckboxSelectMultiple)
  475. # The MultipleHiddenInput widget renders multiple values as hidden fields.
  476. class SongFormHidden(Form):
  477. name = CharField()
  478. composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=MultipleHiddenInput)
  479. f = SongFormHidden(MultiValueDict(dict(name=['Yesterday'], composers=['J', 'P'])), auto_id=False)
  480. self.assertEqual(f.as_ul(), """<li>Name: <input type="text" name="name" value="Yesterday" /><input type="hidden" name="composers" value="J" />
  481. <input type="hidden" name="composers" value="P" /></li>""")
  482. # When using CheckboxSelectMultiple, the framework expects a list of input and
  483. # returns a list of input.
  484. f = SongForm({'name': 'Yesterday'}, auto_id=False)
  485. self.assertEqual(f.errors['composers'], [u'This field is required.'])
  486. f = SongForm({'name': 'Yesterday', 'composers': ['J']}, auto_id=False)
  487. self.assertEqual(f.errors, {})
  488. self.assertEqual(f.cleaned_data['composers'], [u'J'])
  489. self.assertEqual(f.cleaned_data['name'], u'Yesterday')
  490. f = SongForm({'name': 'Yesterday', 'composers': ['J', 'P']}, auto_id=False)
  491. self.assertEqual(f.errors, {})
  492. self.assertEqual(f.cleaned_data['composers'], [u'J', u'P'])
  493. self.assertEqual(f.cleaned_data['name'], u'Yesterday')
  494. def test_escaping(self):
  495. # Validation errors are HTML-escaped when output as HTML.
  496. class EscapingForm(Form):
  497. special_name = CharField(label="<em>Special</em> Field")
  498. special_safe_name = CharField(label=mark_safe("<em>Special</em> Field"))
  499. def clean_special_name(self):
  500. raise ValidationError("Something's wrong with '%s'" % self.cleaned_data['special_name'])
  501. def clean_special_safe_name(self):
  502. raise ValidationError(mark_safe("'<b>%s</b>' is a safe string" % self.cleaned_data['special_safe_name']))
  503. f = EscapingForm({'special_name': "Nothing to escape", 'special_safe_name': "Nothing to escape"}, auto_id=False)
  504. 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>
  505. <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>""")
  506. f = EscapingForm({
  507. 'special_name': "Should escape < & > and <script>alert('xss')</script>",
  508. 'special_safe_name': "<i>Do not escape</i>"
  509. }, auto_id=False)
  510. 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>
  511. <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>""")
  512. def test_validating_multiple_fields(self):
  513. # There are a couple of ways to do multiple-field validation. If you want the
  514. # validation message to be associated with a particular field, implement the
  515. # clean_XXX() method on the Form, where XXX is the field name. As in
  516. # Field.clean(), the clean_XXX() method should return the cleaned value. In the
  517. # clean_XXX() method, you have access to self.cleaned_data, which is a dictionary
  518. # of all the data that has been cleaned *so far*, in order by the fields,
  519. # including the current field (e.g., the field XXX if you're in clean_XXX()).
  520. class UserRegistration(Form):
  521. username = CharField(max_length=10)
  522. password1 = CharField(widget=PasswordInput)
  523. password2 = CharField(widget=PasswordInput)
  524. def clean_password2(self):
  525. if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']:
  526. raise ValidationError(u'Please make sure your passwords match.')
  527. return self.cleaned_data['password2']
  528. f = UserRegistration(auto_id=False)
  529. self.assertEqual(f.errors, {})
  530. f = UserRegistration({}, auto_id=False)
  531. self.assertEqual(f.errors['username'], [u'This field is required.'])
  532. self.assertEqual(f.errors['password1'], [u'This field is required.'])
  533. self.assertEqual(f.errors['password2'], [u'This field is required.'])
  534. f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)
  535. self.assertEqual(f.errors['password2'], [u'Please make sure your passwords match.'])
  536. f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'foo'}, auto_id=False)
  537. self.assertEqual(f.errors, {})
  538. self.assertEqual(f.cleaned_data['username'], u'adrian')
  539. self.assertEqual(f.cleaned_data['password1'], u'foo')
  540. self.assertEqual(f.cleaned_data['password2'], u'foo')
  541. # Another way of doing multiple-field validation is by implementing the
  542. # Form's clean() method. If you do this, any ValidationError raised by that
  543. # method will not be associated with a particular field; it will have a
  544. # special-case association with the field named '__all__'.
  545. # Note that in Form.clean(), you have access to self.cleaned_data, a dictionary of
  546. # all the fields/values that have *not* raised a ValidationError. Also note
  547. # Form.clean() is required to return a dictionary of all clean data.
  548. class UserRegistration(Form):
  549. username = CharField(max_length=10)
  550. password1 = CharField(widget=PasswordInput)
  551. password2 = CharField(widget=PasswordInput)
  552. def clean(self):
  553. if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']:
  554. raise ValidationError(u'Please make sure your passwords match.')
  555. return self.cleaned_data
  556. f = UserRegistration(auto_id=False)
  557. self.assertEqual(f.errors, {})
  558. f = UserRegistration({}, auto_id=False)
  559. 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>
  560. <tr><th>Password1:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="password" name="password1" /></td></tr>
  561. <tr><th>Password2:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="password" name="password2" /></td></tr>""")
  562. self.assertEqual(f.errors['username'], [u'This field is required.'])
  563. self.assertEqual(f.errors['password1'], [u'This field is required.'])
  564. self.assertEqual(f.errors['password2'], [u'This field is required.'])
  565. f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)
  566. self.assertEqual(f.errors['__all__'], [u'Please make sure your passwords match.'])
  567. self.assertEqual(f.as_table(), """<tr><td colspan="2"><ul class="errorlist"><li>Please make sure your passwords match.</li></ul></td></tr>
  568. <tr><th>Username:</th><td><input type="text" name="username" value="adrian" maxlength="10" /></td></tr>
  569. <tr><th>Password1:</th><td><input type="password" name="password1" /></td></tr>
  570. <tr><th>Password2:</th><td><input type="password" name="password2" /></td></tr>""")
  571. self.assertEqual(f.as_ul(), """<li><ul class="errorlist"><li>Please make sure your passwords match.</li></ul></li>
  572. <li>Username: <input type="text" name="username" value="adrian" maxlength="10" /></li>
  573. <li>Password1: <input type="password" name="password1" /></li>
  574. <li>Password2: <input type="password" name="password2" /></li>""")
  575. f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'foo'}, auto_id=False)
  576. self.assertEqual(f.errors, {})
  577. self.assertEqual(f.cleaned_data['username'], u'adrian')
  578. self.assertEqual(f.cleaned_data['password1'], u'foo')
  579. self.assertEqual(f.cleaned_data['password2'], u'foo')
  580. def test_dynamic_construction(self):
  581. # It's possible to construct a Form dynamically by adding to the self.fields
  582. # dictionary in __init__(). Don't forget to call Form.__init__() within the
  583. # subclass' __init__().
  584. class Person(Form):
  585. first_name = CharField()
  586. last_name = CharField()
  587. def __init__(self, *args, **kwargs):
  588. super(Person, self).__init__(*args, **kwargs)
  589. self.fields['birthday'] = DateField()
  590. p = Person(auto_id=False)
  591. self.assertEqual(p.as_table(), """<tr><th>First name:</th><td><input type="text" name="first_name" /></td></tr>
  592. <tr><th>Last name:</th><td><input type="text" name="last_name" /></td></tr>
  593. <tr><th>Birthday:</th><td><input type="text" name="birthday" /></td></tr>""")
  594. # Instances of a dynamic Form do not persist fields from one Form instance to
  595. # the next.
  596. class MyForm(Form):
  597. def __init__(self, data=None, auto_id=False, field_list=[]):
  598. Form.__init__(self, data, auto_id=auto_id)
  599. for field in field_list:
  600. self.fields[field[0]] = field[1]
  601. field_list = [('field1', CharField()), ('field2', CharField())]
  602. my_form = MyForm(field_list=field_list)
  603. self.assertEqual(my_form.as_table(), """<tr><th>Field1:</th><td><input type="text" name="field1" /></td></tr>
  604. <tr><th>Field2:</th><td><input type="text" name="field2" /></td></tr>""")
  605. field_list = [('field3', CharField()), ('field4', CharField())]
  606. my_form = MyForm(field_list=field_list)
  607. self.assertEqual(my_form.as_table(), """<tr><th>Field3:</th><td><input type="text" name="field3" /></td></tr>
  608. <tr><th>Field4:</th><td><input type="text" name="field4" /></td></tr>""")
  609. class MyForm(Form):
  610. default_field_1 = CharField()
  611. default_field_2 = CharField()
  612. def __init__(self, data=None, auto_id=False, field_list=[]):
  613. Form.__init__(self, data, auto_id=auto_id)
  614. for field in field_list:
  615. self.fields[field[0]] = field[1]
  616. field_list = [('field1', CharField()), ('field2', CharField())]
  617. my_form = MyForm(field_list=field_list)
  618. self.assertEqual(my_form.as_table(), """<tr><th>Default field 1:</th><td><input type="text" name="default_field_1" /></td></tr>
  619. <tr><th>Default field 2:</th><td><input type="text" name="default_field_2" /></td></tr>
  620. <tr><th>Field1:</th><td><input type="text" name="field1" /></td></tr>
  621. <tr><th>Field2:</th><td><input type="text" name="field2" /></td></tr>""")
  622. field_list = [('field3', CharField()), ('field4', CharField())]
  623. my_form = MyForm(field_list=field_list)
  624. self.assertEqual(my_form.as_table(), """<tr><th>Default field 1:</th><td><input type="text" name="default_field_1" /></td></tr>
  625. <tr><th>Default field 2:</th><td><input type="text" name="default_field_2" /></td></tr>
  626. <tr><th>Field3:</th><td><input type="text" name="field3" /></td></tr>
  627. <tr><th>Field4:</th><td><input type="text" name="field4" /></td></tr>""")
  628. # Similarly, changes to field attributes do not persist from one Form instance
  629. # to the next.
  630. class Person(Form):
  631. first_name = CharField(required=False)
  632. last_name = CharField(required=False)
  633. def __init__(self, names_required=False, *args, **kwargs):
  634. super(Person, self).__init__(*args, **kwargs)
  635. if names_required:
  636. self.fields['first_name'].required = True
  637. self.fields['first_name'].widget.attrs['class'] = 'required'
  638. self.fields['last_name'].required = True
  639. self.fields['last_name'].widget.attrs['class'] = 'required'
  640. f = Person(names_required=False)
  641. self.assertEqual(f['first_name'].field.required, f['last_name'].field.required, (False, False))
  642. self.assertEqual(f['first_name'].field.widget.attrs, f['last_name'].field.widget.attrs, ({}, {}))
  643. f = Person(names_required=True)
  644. self.assertEqual(f['first_name'].field.required, f['last_name'].field.required, (True, True))
  645. self.assertEqual(f['first_name'].field.widget.attrs, f['last_name'].field.widget.attrs, ({'class': 'required'}, {'class': 'required'}))
  646. f = Person(names_required=False)
  647. self.assertEqual(f['first_name'].field.required, f['last_name'].field.required, (False, False))
  648. self.assertEqual(f['first_name'].field.widget.attrs, f['last_name'].field.widget.attrs, ({}, {}))
  649. class Person(Form):
  650. first_name = CharField(max_length=30)
  651. last_name = CharField(max_length=30)
  652. def __init__(self, name_max_length=None, *args, **kwargs):
  653. super(Person, self).__init__(*args, **kwargs)
  654. if name_max_length:
  655. self.fields['first_name'].max_length = name_max_length
  656. self.fields['last_name'].max_length = name_max_length
  657. f = Person(name_max_length=None)
  658. self.assertEqual(f['first_name'].field.max_length, f['last_name'].field.max_length, (30, 30))
  659. f = Person(name_max_length=20)
  660. self.assertEqual(f['first_name'].field.max_length, f['last_name'].field.max_length, (20, 20))
  661. f = Person(name_max_length=None)
  662. self.assertEqual(f['first_name'].field.max_length, f['last_name'].field.max_length, (30, 30))
  663. # Similarly, choices do not persist from one Form instance to the next.
  664. # Refs #15127.
  665. class Person(Form):
  666. first_name = CharField(required=False)
  667. last_name = CharField(required=False)
  668. gender = ChoiceField(choices=(('f', 'Female'), ('m', 'Male')))
  669. def __init__(self, allow_unspec_gender=False, *args, **kwargs):
  670. super(Person, self).__init__(*args, **kwargs)
  671. if allow_unspec_gender:
  672. self.fields['gender'].choices += (('u', 'Unspecified'),)
  673. f = Person()
  674. self.assertEqual(f['gender'].field.choices, [('f', 'Female'), ('m', 'Male')])
  675. f = Person(allow_unspec_gender=True)
  676. self.assertEqual(f['gender'].field.choices, [('f', 'Female'), ('m', 'Male'), ('u', 'Unspecified')])
  677. f = Person()
  678. self.assertEqual(f['gender'].field.choices, [('f', 'Female'), ('m', 'Male')])
  679. def test_validators_independence(self):
  680. """ Test that we are able to modify a form field validators list without polluting
  681. other forms """
  682. from django.core.validators import MaxValueValidator
  683. class MyForm(Form):
  684. myfield = CharField(max_length=25)
  685. f1 = MyForm()
  686. f2 = MyForm()
  687. f1.fields['myfield'].validators[0] = MaxValueValidator(12)
  688. self.assertFalse(f1.fields['myfield'].validators[0] == f2.fields['myfield'].validators[0])
  689. def test_hidden_widget(self):
  690. # HiddenInput widgets are displayed differently in the as_table(), as_ul())
  691. # and as_p() output of a Form -- their verbose names are not displayed, and a
  692. # separate row is not displayed. They're displayed in the last row of the
  693. # form, directly after that row's form element.
  694. class Person(Form):
  695. first_name = CharField()
  696. last_name = CharField()
  697. hidden_text = CharField(widget=HiddenInput)
  698. birthday = DateField()
  699. p = Person(auto_id=False)
  700. self.assertEqual(p.as_table(), """<tr><th>First name:</th><td><input type="text" name="first_name" /></td></tr>
  701. <tr><th>Last name:</th><td><input type="text" name="last_name" /></td></tr>
  702. <tr><th>Birthday:</th><td><input type="text" name="birthday" /><input type="hidden" name="hidden_text" /></td></tr>""")
  703. self.assertEqual(p.as_ul(), """<li>First name: <input type="text" name="first_name" /></li>
  704. <li>Last name: <input type="text" name="last_name" /></li>
  705. <li>Birthday: <input type="text" name="birthday" /><input type="hidden" name="hidden_text" /></li>""")
  706. self.assertEqual(p.as_p(), """<p>First name: <input type="text" name="first_name" /></p>
  707. <p>Last name: <input type="text" name="last_name" /></p>
  708. <p>Birthday: <input type="text" name="birthday" /><input type="hidden" name="hidden_text" /></p>""")
  709. # With auto_id set, a HiddenInput still gets an ID, but it doesn't get a label.
  710. p = Person(auto_id='id_%s')
  711. 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>
  712. <tr><th><label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" id="id_last_name" /></td></tr>
  713. <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>""")
  714. 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>
  715. <li><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></li>
  716. <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>""")
  717. 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>
  718. <p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></p>
  719. <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>""")
  720. # If a field with a HiddenInput has errors, the as_table() and as_ul() output
  721. # will include the error message(s) with the text "(Hidden field [fieldname]) "
  722. # prepended. This message is displayed at the top of the output, regardless of
  723. # its field's order in the form.
  724. p = Person({'first_name': 'John', 'last_name': 'Lennon', 'birthday': '1940-10-9'}, auto_id=False)
  725. 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>
  726. <tr><th>First name:</th><td><input type="text" name="first_name" value="John" /></td></tr>
  727. <tr><th>Last name:</th><td><input type="text" name="last_name" value="Lennon" /></td></tr>
  728. <tr><th>Birthday:</th><td><input type="text" name="birthday" value="1940-10-9" /><input type="hidden" name="hidden_text" /></td></tr>""")
  729. self.assertEqual(p.as_ul(), """<li><ul class="errorlist"><li>(Hidden field hidden_text) This field is required.</li></ul></li>
  730. <li>First name: <input type="text" name="first_name" value="John" /></li>
  731. <li>Last name: <input type="text" name="last_name" value="Lennon" /></li>
  732. <li>Birthday: <input type="text" name="birthday" value="1940-10-9" /><input type="hidden" name="hidden_text" /></li>""")
  733. self.assertEqual(p.as_p(), """<ul class="errorlist"><li>(Hidden field hidden_text) This field is required.</li></ul>
  734. <p>First name: <input type="text" name="first_name" value="John" /></p>
  735. <p>Last name: <input type="text" name="last_name" value="Lennon" /></p>
  736. <p>Birthday: <input type="text" name="birthday" value="1940-10-9" /><input type="hidden" name="hidden_text" /></p>""")
  737. # A corner case: It's possible for a form to have only HiddenInputs.
  738. class TestForm(Form):
  739. foo = CharField(widget=HiddenInput)
  740. bar = CharField(widget=HiddenInput)
  741. p = TestForm(auto_id=False)
  742. self.assertEqual(p.as_table(), '<input type="hidden" name="foo" /><input type="hidden" name="bar" />')
  743. self.assertEqual(p.as_ul(), '<input type="hidden" name="foo" /><input type="hidden" name="bar" />')
  744. self.assertEqual(p.as_p(), '<input type="hidden" name="foo" /><input type="hidden" name="bar" />')
  745. def test_field_order(self):
  746. # A Form's fields are displayed in the same order in which they were defined.
  747. class TestForm(Form):
  748. field1 = CharField()
  749. field2 = CharField()
  750. field3 = CharField()
  751. field4 = CharField()
  752. field5 = CharField()
  753. field6 = CharField()
  754. field7 = CharField()
  755. field8 = CharField()
  756. field9 = CharField()
  757. field10 = CharField()
  758. field11 = CharField()
  759. field12 = CharField()
  760. field13 = CharField()
  761. field14 = CharField()
  762. p = TestForm(auto_id=False)
  763. self.assertEqual(p.as_table(), """<tr><th>Field1:</th><td><input type="text" name="field1" /></td></tr>
  764. <tr><th>Field2:</th><td><input type="text" name="field2" /></td></tr>
  765. <tr><th>Field3:</th><td><input type="text" name="field3" /></td></tr>
  766. <tr><th>Field4:</th><td><input type="text" name="field4" /></td></tr>
  767. <tr><th>Field5:</th><td><input type="text" name="field5" /></td></tr>
  768. <tr><th>Field6:</th><td><input type="text" name="field6" /></td></tr>
  769. <tr><th>Field7:</th><td><input type="text" name="field7" /></td></tr>
  770. <tr><th>Field8:</th><td><input type="text" name="field8" /></td></tr>
  771. <tr><th>Field9:</th><td><input type="text" name="field9" /></td></tr>
  772. <tr><th>Field10:</th><td><input type="text" name="field10" /></td></tr>
  773. <tr><th>Field11:</th><td><input type="text" name="field11" /></td></tr>
  774. <tr><th>Field12:</th><td><input type="text" name="field12" /></td></tr>
  775. <tr><th>Field13:</th><td><input type="text" name="field13" /></td></tr>
  776. <tr><th>Field14:</th><td><input type="text" name="field14" /></td></tr>""")
  777. def test_form_html_attributes(self):
  778. # Some Field classes have an effect on the HTML attributes of their associated
  779. # Widget. If you set max_length in a CharField and its associated widget is
  780. # either a TextInput or PasswordInput, then the widget's rendered HTML will
  781. # include the "maxlength" attribute.
  782. class UserRegistration(Form):
  783. username = CharField(max_length=10) # uses TextInput by default
  784. password = CharField(max_length=10, widget=PasswordInput)
  785. realname = CharField(max_length=10, widget=TextInput) # redundantly define widget, just to test
  786. address = CharField() # no max_length defined here
  787. p = UserRegistration(auto_id=False)
  788. self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" /></li>
  789. <li>Password: <input type="password" name="password" maxlength="10" /></li>
  790. <li>Realname: <input type="text" name="realname" maxlength="10" /></li>
  791. <li>Address: <input type="text" name="address" /></li>""")
  792. # If you specify a custom "attrs" that includes the "maxlength" attribute,
  793. # the Field's max_length attribute will override whatever "maxlength" you specify
  794. # in "attrs".
  795. class UserRegistration(Form):
  796. username = CharField(max_length=10, widget=TextInput(attrs={'maxlength': 20}))
  797. password = CharField(max_length=10, widget=PasswordInput)
  798. p = UserRegistration(auto_id=False)
  799. self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" /></li>
  800. <li>Password: <input type="password" name="password" maxlength="10" /></li>""")
  801. def test_specifying_labels(self):
  802. # You can specify the label for a field by using the 'label' argument to a Field
  803. # class. If you don't specify 'label', Django will use the field name with
  804. # underscores converted to spaces, and the initial letter capitalized.
  805. class UserRegistration(Form):
  806. username = CharField(max_length=10, label='Your username')
  807. password1 = CharField(widget=PasswordInput)
  808. password2 = CharField(widget=PasswordInput, label='Password (again)')
  809. p = UserRegistration(auto_id=False)
  810. self.assertEqual(p.as_ul(), """<li>Your username: <input type="text" name="username" maxlength="10" /></li>
  811. <li>Password1: <input type="password" name="password1" /></li>
  812. <li>Password (again): <input type="password" name="password2" /></li>""")
  813. # Labels for as_* methods will only end in a colon if they don't end in other
  814. # punctuation already.
  815. class Questions(Form):
  816. q1 = CharField(label='The first question')
  817. q2 = CharField(label='What is your name?')
  818. q3 = CharField(label='The answer to life is:')
  819. q4 = CharField(label='Answer this question!')
  820. q5 = CharField(label='The last question. Period.')
  821. self.assertEqual(Questions(auto_id=False).as_p(), """<p>The first question: <input type="text" name="q1" /></p>
  822. <p>What is your name? <input type="text" name="q2" /></p>
  823. <p>The answer to life is: <input type="text" name="q3" /></p>
  824. <p>Answer this question! <input type="text" name="q4" /></p>
  825. <p>The last question. Period. <input type="text" name="q5" /></p>""")
  826. self.assertEqual(Questions().as_p(), """<p><label for="id_q1">The first question:</label> <input type="text" name="q1" id="id_q1" /></p>
  827. <p><label for="id_q2">What is your name?</label> <input type="text" name="q2" id="id_q2" /></p>
  828. <p><label for="id_q3">The answer to life is:</label> <input type="text" name="q3" id="id_q3" /></p>
  829. <p><label for="id_q4">Answer this question!</label> <input type="text" name="q4" id="id_q4" /></p>
  830. <p><label for="id_q5">The last question. Period.</label> <input type="text" name="q5" id="id_q5" /></p>""")
  831. # A label can be a Unicode object or a bytestring with special characters.
  832. class UserRegistration(Form):
  833. username = CharField(max_length=10, label='ŠĐĆŽćžšđ')
  834. password = CharField(widget=PasswordInput, label=u'\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111')
  835. p = UserRegistration(auto_id=False)
  836. 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>')
  837. # If a label is set to the empty string for a field, that field won't get a label.
  838. class UserRegistration(Form):
  839. username = CharField(max_length=10, label='')
  840. password = CharField(widget=PasswordInput)
  841. p = UserRegistration(auto_id=False)
  842. self.assertEqual(p.as_ul(), """<li> <input type="text" name="username" maxlength="10" /></li>
  843. <li>Password: <input type="password" name="password" /></li>""")
  844. p = UserRegistration(auto_id='id_%s')
  845. self.assertEqual(p.as_ul(), """<li> <input id="id_username" type="text" name="username" maxlength="10" /></li>
  846. <li><label for="id_password">Password:</label> <input type="password" name="password" id="id_password" /></li>""")
  847. # If label is None, Django will auto-create the label from the field name. This
  848. # is default behavior.
  849. class UserRegistration(Form):
  850. username = CharField(max_length=10, label=None)
  851. password = CharField(widget=PasswordInput)
  852. p = UserRegistration(auto_id=False)
  853. self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" /></li>
  854. <li>Password: <input type="password" name="password" /></li>""")
  855. p = UserRegistration(auto_id='id_%s')
  856. self.assertEqual(p.as_ul(), """<li><label for="id_username">Username:</label> <input id="id_username" type="text" name="username" maxlength="10" /></li>
  857. <li><label for="id_password">Password:</label> <input type="password" name="password" id="id_password" /></li>""")
  858. def test_label_suffix(self):
  859. # You can specify the 'label_suffix' argument to a Form class to modify the
  860. # punctuation symbol used at the end of a label. By default, the colon (:) is
  861. # used, and is only appended to the label if the label doesn't already end with a
  862. # punctuation symbol: ., !, ? or :. If you specify a different suffix, it will
  863. # be appended regardless of the last character of the label.
  864. class FavoriteForm(Form):
  865. color = CharField(label='Favorite color?')
  866. animal = CharField(label='Favorite animal')
  867. f = FavoriteForm(auto_id=False)
  868. self.assertEqual(f.as_ul(), """<li>Favorite color? <input type="text" name="color" /></li>
  869. <li>Favorite animal: <input type="text" name="animal" /></li>""")
  870. f = FavoriteForm(auto_id=False, label_suffix='?')
  871. self.assertEqual(f.as_ul(), """<li>Favorite color? <input type="text" name="color" /></li>
  872. <li>Favorite animal? <input type="text" name="animal" /></li>""")
  873. f = FavoriteForm(auto_id=False, label_suffix='')
  874. self.assertEqual(f.as_ul(), """<li>Favorite color? <input type="text" name="color" /></li>
  875. <li>Favorite animal <input type="text" name="animal" /></li>""")
  876. f = FavoriteForm(auto_id=False, label_suffix=u'\u2192')
  877. 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>')
  878. def test_initial_data(self):
  879. # You can specify initial data for a field by using the 'initial' argument to a
  880. # Field class. This initial data is displayed when a Form is rendered with *no*
  881. # data. It is not displayed when a Form is rendered with any data (including an
  882. # empty dictionary). Also, the initial value is *not* used if data for a
  883. # particular required field isn't provided.
  884. class UserRegistration(Form):
  885. username = CharField(max_length=10, initial='django')
  886. password = CharField(widget=PasswordInput)
  887. # Here, we're not submitting any data, so the initial value will be displayed.)
  888. p = UserRegistration(auto_id=False)
  889. self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="django" maxlength="10" /></li>
  890. <li>Password: <input type="password" name="password" /></li>""")
  891. # Here, we're submitting data, so the initial value will *not* be displayed.
  892. p = UserRegistration({}, auto_id=False)
  893. 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>
  894. <li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>""")
  895. p = UserRegistration({'username': u''}, auto_id=False)
  896. 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>
  897. <li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>""")
  898. p = UserRegistration({'username': u'foo'}, auto_id=False)
  899. self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="foo" maxlength="10" /></li>
  900. <li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>""")
  901. # An 'initial' value is *not* used as a fallback if data is not provided. In this
  902. # example, we don't provide a value for 'username', and the form raises a
  903. # validation error rather than using the initial value for 'username'.
  904. p = UserRegistration({'password': 'secret'})
  905. self.assertEqual(p.errors['username'], [u'This field is required.'])
  906. self.assertFalse(p.is_valid())
  907. def test_dynamic_initial_data(self):
  908. # The previous technique dealt with "hard-coded" initial data, but it's also
  909. # possible to specify initial data after you've already created the Form class
  910. # (i.e., at runtime). Use the 'initial' parameter to the Form constructor. This
  911. # should be a dictionary containing initial values for one or more fields in the
  912. # form, keyed by field name.
  913. class UserRegistration(Form):
  914. username = CharField(max_length=10)
  915. password = CharField(widget=PasswordInput)
  916. # Here, we're not submitting any data, so the initial value will be displayed.)
  917. p = UserRegistration(initial={'username': 'django'}, auto_id=False)
  918. self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="django" maxlength="10" /></li>
  919. <li>Password: <input type="password" name="password" /></li>""")
  920. p = UserRegistration(initial={'username': 'stephane'}, auto_id=False)
  921. self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="stephane" maxlength="10" /></li>
  922. <li>Password: <input type="password" name="password" /></li>""")
  923. # The 'initial' parameter is meaningless if you pass data.
  924. p = UserRegistration({}, initial={'username': 'django'}, auto_id=False)
  925. 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>
  926. <li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>""")
  927. p = UserRegistration({'username': u''}, initial={'username': 'django'}, auto_id=False)
  928. 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>
  929. <li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>""")
  930. p = UserRegistration({'username': u'foo'}, initial={'username': 'django'}, auto_id=False)
  931. self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="foo" maxlength="10" /></li>
  932. <li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>""")
  933. # A dynamic 'initial' value is *not* used as a fallback if data is not provided.
  934. # In this example, we don't provide a value for 'username', and the form raises a
  935. # validation error rather than using the initial value for 'username'.
  936. p = UserRegistration({'password': 'secret'}, initial={'username': 'django'})
  937. self.assertEqual(p.errors['username'], [u'This field is required.'])
  938. self.assertFalse(p.is_valid())
  939. # If a Form defines 'initial' *and* 'initial' is passed as a parameter to Form(),
  940. # then the latter will get precedence.
  941. class UserRegistration(Form):
  942. username = CharField(max_length=10, initial='django')
  943. password = CharField(widget=PasswordInput)
  944. p = UserRegistration(initial={'username': 'babik'}, auto_id=False)
  945. self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="babik" maxlength="10" /></li>
  946. <li>Password: <input type="password" name="password" /></li>""")
  947. def test_callable_initial_data(self):
  948. # The previous technique dealt with raw values as initial data, but it's also
  949. # possible to specify callable data.
  950. class UserRegistration(Form):
  951. username = CharField(max_length=10)
  952. password = CharField(widget=PasswordInput)
  953. options = MultipleChoiceField(choices=[('f','foo'),('b','bar'),('w','whiz')])
  954. # We need to define functions that get called later.)
  955. def initial_django():
  956. return 'django'
  957. def initial_stephane():
  958. return 'stephane'
  959. def initial_options():
  960. return ['f','b']
  961. def initial_other_options():
  962. return ['b','w']
  963. # Here, we're not submitting any data, so the initial value will be displayed.)
  964. p = UserRegistration(initial={'username': initial_django, 'options': initial_options}, auto_id=False)
  965. self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="django" maxlength="10" /></li>
  966. <li>Password: <input type="password" name="password" /></li>
  967. <li>Options: <select multiple="multiple" name="options">
  968. <option value="f" selected="selected">foo</option>
  969. <option value="b" selected="selected">bar</option>
  970. <option value="w">whiz</option>
  971. </select></li>""")
  972. # The 'initial' parameter is meaningless if you pass data.
  973. p = UserRegistration({}, initial={'username': initial_django, 'options': initial_options}, auto_id=False)
  974. 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>
  975. <li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>
  976. <li><ul class="errorlist"><li>This field is required.</li></ul>Options: <select multiple="multiple" name="options">
  977. <option value="f">foo</option>
  978. <option value="b">bar</option>
  979. <option value="w">whiz</option>
  980. </select></li>""")
  981. p = UserRegistration({'username': u''}, initial={'username': initial_django}, auto_id=False)
  982. 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>
  983. <li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>
  984. <li><ul class="errorlist"><li>This field is required.</li></ul>Options: <select multiple="multiple" name="options">
  985. <option value="f">foo</option>
  986. <option value="b">bar</option>
  987. <option value="w">whiz</option>
  988. </select></li>""")
  989. p = UserRegistration({'username': u'foo', 'options':['f','b']}, initial={'username': initial_django}, auto_id=False)
  990. self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="foo" maxlength="10" /></li>
  991. <li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>
  992. <li>Options: <select multiple="multiple" name="options">
  993. <option value="f" selected="selected">foo</option>
  994. <option value="b" selected="selected">bar</option>
  995. <option value="w">whiz</option>
  996. </select></li>""")
  997. # A callable 'initial' value is *not* used as a fallback if data is not provided.
  998. # In this example, we don't provide a value for 'username', and the form raises a
  999. # validation error rather than using the initial value for 'username'.
  1000. p = UserRegistration({'password': 'secret'}, initial={'username': initial_django, 'options': initial_options})
  1001. self.assertEqual(p.errors['username'], [u'This field is required.'])
  1002. self.assertFalse(p.is_valid())
  1003. # If a Form defines 'initial' *and* 'initial' is passed as a parameter to Form(),
  1004. # then the latter will get precedence.
  1005. class UserRegistration(Form):
  1006. username = CharField(max_length=10, initial=initial_django)
  1007. password = CharField(widget=PasswordInput)
  1008. options = MultipleChoiceField(choices=[('f','foo'),('b','bar'),('w','whiz')], initial=initial_other_options)
  1009. p = UserRegistration(auto_id=False)
  1010. self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="django" maxlength="10" /></li>
  1011. <li>Password: <input type="password" name="password" /></li>
  1012. <li>Options: <select multiple="multiple" name="options">
  1013. <option value="f">foo</option>
  1014. <option value="b" selected="selected">bar</option>
  1015. <option value="w" selected="selected">whiz</option>
  1016. </select></li>""")
  1017. p = UserRegistration(initial={'username': initial_stephane, 'options': initial_options}, auto_id=False)
  1018. self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="stephane" maxlength="10" /></li>
  1019. <li>Password: <input type="password" name="password" /></li>
  1020. <li>Options: <select multiple="multiple" name="options">
  1021. <option value="f" selected="selected">foo</option>
  1022. <option value="b" selected="selected">bar</option>
  1023. <option value="w">whiz</option>
  1024. </select></li>""")
  1025. def test_boundfield_values(self):
  1026. # It's possible to get to the value which would be used for rendering
  1027. # the widget for a field by using the BoundField's value method.
  1028. class UserRegistration(Form):
  1029. username = CharField(max_length=10, initial='djangonaut')
  1030. password = CharField(widget=PasswordInput)
  1031. unbound = UserRegistration()
  1032. bound = UserRegistration({'password': 'foo'})
  1033. self.assertEqual(bound['username'].value(), None)
  1034. self.assertEqual(unbound['username'].value(), 'djangonaut')
  1035. self.assertEqual(bound['password'].value(), 'foo')
  1036. self.assertEqual(unbound['password'].value(), None)
  1037. def test_help_text(self):
  1038. # You can specify descriptive text for a field by using the 'help_text' argument)
  1039. class UserRegistration(Form):
  1040. username = CharField(max_length=10, help_text='e.g., user@example.com')
  1041. password = CharField(widget=PasswordInput, help_text='Choose wisely.')
  1042. p = UserRegistration(auto_id=False)
  1043. self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" /> <span class="helptext">e.g., user@example.com</span></li>
  1044. <li>Password: <input type="password" name="password" /> <span class="helptext">Choose wisely.</span></li>""")
  1045. self.assertEqual(p.as_p(), """<p>Username: <input type="text" name="username" maxlength="10" /> <span class="helptext">e.g., user@example.com</span></p>
  1046. <p>Password: <input type="password" name="password" /> <span class="helptext">Choose wisely.</span></p>""")
  1047. 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>
  1048. <tr><th>Password:</th><td><input type="password" name="password" /><br /><span class="helptext">Choose wisely.</span></td></tr>""")
  1049. # The help text is displayed whether or not data is provided for the form.
  1050. p = UserRegistration({'username': u'foo'}, auto_id=False)
  1051. 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>
  1052. <li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /> <span class="helptext">Choose wisely.</span></li>""")
  1053. # help_text is not displayed for hidden fields. It can be used for documentation
  1054. # purposes, though.
  1055. class UserRegistration(Form):
  1056. username = CharField(max_length=10, help_text='e.g., user@example.com')
  1057. password = CharField(widget=PasswordInput)
  1058. next = CharField(widget=HiddenInput, initial='/', help_text='Redirect destination')
  1059. p = UserRegistration(auto_id=False)
  1060. self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" /> <span class="helptext">e.g., user@example.com</span></li>
  1061. <li>Password: <input type="password" name="password" /><input type="hidden" name="next" value="/" /></li>""")
  1062. # Help text can include arbitrary Unicode characters.
  1063. class UserRegistration(Form):
  1064. username = CharField(max_length=10, help_text='ŠĐĆŽćžšđ')
  1065. p = UserRegistration(auto_id=False)
  1066. 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>')
  1067. def test_subclassing_forms(self):
  1068. # You can subclass a Form to add fields. The resulting form subclass will have
  1069. # all of the fields of the parent Form, plus whichever fields you define in the
  1070. # subclass.
  1071. class Person(Form):
  1072. first_name = CharField()
  1073. last_name = CharField()
  1074. birthday = DateField()
  1075. class Musician(Person):
  1076. instrument = CharField()
  1077. p = Person(auto_id=False)
  1078. self.assertEqual(p.as_ul(), """<li>First name: <input type="text" name="first_name" /></li>
  1079. <li>Last name: <input type="text" name="last_name" /></li>
  1080. <li>Birthday: <input type="text" name="birthday" /></li>""")
  1081. m = Musician(auto_id=False)
  1082. self.assertEqual(m.as_ul(), """<li>First name: <input type="text" name="first_name" /></li>
  1083. <li>Last name: <input type="text" name="last_name" /></li>
  1084. <li>Birthday: <input type="text" name="birthday" /></li>
  1085. <li>Instrument: <input type="text" name="instrument" /></li>""")
  1086. # Yes, you can subclass multiple forms. The fields are added in the order in
  1087. # which the parent classes are listed.
  1088. class Person(Form):
  1089. first_name = CharField()
  1090. last_name = CharField()
  1091. birthday = DateField()
  1092. class Instrument(Form):
  1093. instrument = CharField()
  1094. class Beatle(Person, Instrument):
  1095. haircut_type = CharField()
  1096. b = Beatle(auto_id=False)
  1097. self.assertEqual(b.as_ul(), """<li>First name: <input type="text" name="first_name" /></li>
  1098. <li>Last name: <input type="text" name="last_name" /></li>
  1099. <li>Birthday: <input type="text" name="birthday" /></li>
  1100. <li>Instrument: <input type="text" name="instrument" /></li>
  1101. <li>Haircut type: <input type="text" name="haircut_type" /></li>""")
  1102. def test_forms_with_prefixes(self):
  1103. # Sometimes it's necessary to have multiple forms display on the same HTML page,
  1104. # or multiple copies of the same form. We can accomplish this with form prefixes.
  1105. # Pass the keyword argument 'prefix' to the Form constructor to use this feature.
  1106. # This value will be prepended to each HTML form field name. One way to think
  1107. # about this is "namespaces for HTML forms". Notice that in the data argument,
  1108. # each field's key has the prefix, in this case 'person1', prepended to the
  1109. # actual field name.
  1110. class Person(Form):
  1111. first_name = CharField()
  1112. last_name = CharField()
  1113. birthday = DateField()
  1114. data = {
  1115. 'person1-first_name': u'John',
  1116. 'person1-last_name': u'Lennon',
  1117. 'person1-birthday': u'1940-10-9'
  1118. }
  1119. p = Person(data, prefix='person1')
  1120. 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>
  1121. <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>
  1122. <li><label for="id_person1-birthday">Birthday:</label> <input type="text" name="person1-birthday" value="1940-10-9" id="id_person1-birthday" /></li>""")
  1123. self.assertEqual(str(p['first_name']), '<input type="text" name="person1-first_name" value="John" id="id_person1-first_name" />')
  1124. self.assertEqual(str(p['last_name']), '<input type="text" name="person1-last_name" value="Lennon" id="id_person1-last_name" />')
  1125. self.assertEqual(str(p['birthday']), '<input type="text" name="person1-birthday" value="1940-10-9" id="id_person1-birthday" />')
  1126. self.assertEqual(p.errors, {})
  1127. self.assertTrue(p.is_valid())
  1128. self.assertEqual(p.cleaned_data['first_name'], u'John')
  1129. self.assertEqual(p.cleaned_data['last_name'], u'Lennon')
  1130. self.assertEqual(p.cleaned_data['birthday'], datetime.date(1940, 10, 9))
  1131. # Let's try submitting some bad data to make sure form.errors and field.errors
  1132. # work as expected.
  1133. data = {
  1134. 'person1-first_name': u'',
  1135. 'person1-last_name': u'',
  1136. 'person1-birthday': u''
  1137. }
  1138. p = Person(data, prefix='person1')
  1139. self.assertEqual(p.errors['first_name'], [u'This field is required.'])
  1140. self.assertEqual(p.errors['last_name'], [u'This field is required.'])
  1141. self.assertEqual(p.errors['birthday'], [u'This field is required.'])
  1142. self.assertEqual(p['first_name'].errors, [u'This field is required.'])
  1143. try:
  1144. p['person1-first_name'].errors
  1145. self.fail('Attempts to access non-existent fields should fail.')
  1146. except KeyError:
  1147. pass
  1148. # In this example, the data doesn't have a prefix, but the form requires it, so
  1149. # the form doesn't "see" the fields.
  1150. data = {
  1151. 'first_name': u'John',
  1152. 'last_name': u'Lennon',
  1153. 'birthday': u'1940-10-9'
  1154. }
  1155. p = Person(data, prefix='person1')
  1156. self.assertEqual(p.errors['first_name'], [u'This field is required.'])
  1157. self.assertEqual(p.errors['last_name'], [u'This field is required.'])
  1158. self.assertEqual(p.errors['birthday'], [u'This field is required.'])
  1159. # With prefixes, a single data dictionary can hold data for multiple instances
  1160. # of the same form.
  1161. data = {
  1162. 'person1-first_name': u'John',
  1163. 'person1-last_name': u'Lennon',
  1164. 'person1-birthday': u'1940-10-9',
  1165. 'person2-first_name': u'Jim',
  1166. 'person2-last_name': u'Morrison',
  1167. 'person2-birthday': u'1943-12-8'
  1168. }
  1169. p1 = Person(data, prefix='person1')
  1170. self.assertTrue(p1.is_valid())
  1171. self.assertEqual(p1.cleaned_data['first_name'], u'John')
  1172. self.assertEqual(p1.cleaned_data['last_name'], u'Lennon')
  1173. self.assertEqual(p1.cleaned_data['birthday'], datetime.date(1940, 10, 9))
  1174. p2 = Person(data, prefix='person2')
  1175. self.assertTrue(p2.is_valid())
  1176. self.assertEqual(p2.cleaned_data['first_name'], u'Jim')
  1177. self.assertEqual(p2.cleaned_data['last_name'], u'Morrison')
  1178. self.assertEqual(p2.cleaned_data['birthday'], datetime.date(1943, 12, 8))
  1179. # By default, forms append a hyphen between the prefix and the field name, but a
  1180. # form can alter that behavior by implementing the add_prefix() method. This
  1181. # method takes a field name and returns the prefixed field, according to
  1182. # self.prefix.
  1183. class Person(Form):
  1184. first_name = CharField()
  1185. last_name = CharField()
  1186. birthday = DateField()
  1187. def add_prefix(self, field_name):
  1188. return self.prefix and '%s-prefix-%s' % (self.prefix, field_name) or field_name
  1189. p = Person(prefix='foo')
  1190. 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>
  1191. <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>
  1192. <li><label for="id_foo-prefix-birthday">Birthday:</label> <input type="text" name="foo-prefix-birthday" id="id_foo-prefix-birthday" /></li>""")
  1193. data = {
  1194. 'foo-prefix-first_name': u'John',
  1195. 'foo-prefix-last_name': u'Lennon',
  1196. 'foo-prefix-birthday': u'1940-10-9'
  1197. }
  1198. p = Person(data, prefix='foo')
  1199. self.assertTrue(p.is_valid())
  1200. self.assertEqual(p.cleaned_data['first_name'], u'John')
  1201. self.assertEqual(p.cleaned_data['last_name'], u'Lennon')
  1202. self.assertEqual(p.cleaned_data['birthday'], datetime.date(1940, 10, 9))
  1203. def test_forms_with_null_boolean(self):
  1204. # NullBooleanField is a bit of a special case because its presentation (widget)
  1205. # is different than its data. This is handled transparently, though.
  1206. class Person(Form):
  1207. name = CharField()
  1208. is_cool = NullBooleanField()
  1209. p = Person({'name': u'Joe'}, auto_id=False)
  1210. self.assertEqual(str(p['is_cool']), """<select name="is_cool">
  1211. <option value="1" selected="selected">Unknown</option>
  1212. <option value="2">Yes</option>
  1213. <option value="3">No</option>
  1214. </select>""")
  1215. p = Person({'name': u'Joe', 'is_cool': u'1'}, auto_id=False)
  1216. self.assertEqual(str(p['is_cool']), """<select name="is_cool">
  1217. <option value="1" selected="selected">Unknown</option>
  1218. <option value="2">Yes</option>
  1219. <option value="3">No</option>
  1220. </select>""")
  1221. p = Person({'name': u'Joe', 'is_cool': u'2'}, auto_id=False)
  1222. self.assertEqual(str(p['is_cool']), """<select name="is_cool">
  1223. <option value="1">Unknown</option>
  1224. <option value="2" selected="selected">Yes</option>
  1225. <option value="3">No</option>
  1226. </select>""")
  1227. p = Person({'name': u'Joe', 'is_cool': u'3'}, auto_id=False)
  1228. self.assertEqual(str(p['is_cool']), """<select name="is_cool">
  1229. <option value="1">Unknown</option>
  1230. <option value="2">Yes</option>
  1231. <option value="3" selected="selected">No</option>
  1232. </select>""")
  1233. p = Person({'name': u'Joe', 'is_cool': True}, auto_id=False)
  1234. self.assertEqual(str(p['is_cool']), """<select name="is_cool">
  1235. <option value="1">Unknown</option>
  1236. <option value="2" selected="selected">Yes</option>
  1237. <option value="3">No</option>
  1238. </select>""")
  1239. p = Person({'name': u'Joe', 'is_cool': False}, auto_id=False)
  1240. self.assertEqual(str(p['is_cool']), """<select name="is_cool">
  1241. <option value="1">Unknown</option>
  1242. <option value="2">Yes</option>
  1243. <option value="3" selected="selected">No</option>
  1244. </select>""")
  1245. def test_forms_with_file_fields(self):
  1246. # FileFields are a special case because they take their data from the request.FILES,
  1247. # not request.POST.
  1248. class FileForm(Form):
  1249. file1 = FileField()
  1250. f = FileForm(auto_id=False)
  1251. self.assertEqual(f.as_table(), '<tr><th>File1:</th><td><input type="file" name="file1" /></td></tr>')
  1252. f = FileForm(data={}, files={}, auto_id=False)
  1253. 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>')
  1254. f = FileForm(data={}, files={'file1': SimpleUploadedFile('name', '')}, auto_id=False)
  1255. 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>')
  1256. f = FileForm(data={}, files={'file1': 'something that is not a file'}, auto_id=False)
  1257. 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>')
  1258. f = FileForm(data={}, files={'file1': SimpleUploadedFile('name', 'some content')}, auto_id=False)
  1259. self.assertEqual(f.as_table(), '<tr><th>File1:</th><td><input type="file" name="file1" /></td></tr>')
  1260. self.assertTrue(f.is_valid())
  1261. f = FileForm(data={}, files={'file1': SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह')}, auto_id=False)
  1262. self.assertEqual(f.as_table(), '<tr><th>File1:</th><td><input type="file" name="file1" /></td></tr>')
  1263. def test_basic_processing_in_view(self):
  1264. class UserRegistration(Form):
  1265. username = CharField(max_length=10)
  1266. password1 = CharField(widget=PasswordInput)
  1267. password2 = CharField(widget=PasswordInput)
  1268. def clean(self):
  1269. if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']:
  1270. raise ValidationError(u'Please make sure your passwords match.')
  1271. return self.cleaned_data
  1272. def my_function(method, post_data):
  1273. if method == 'POST':
  1274. form = UserRegistration(post_data, auto_id=False)
  1275. else:
  1276. form = UserRegistration(auto_id=False)
  1277. if form.is_valid():
  1278. return 'VALID: %r' % form.cleaned_data
  1279. t = Template('<form action="" method="post">\n<table>\n{{ form }}\n</table>\n<input type="submit" />\n</form>')
  1280. return t.render(Context({'form': form}))
  1281. # Case 1: GET (an empty form, with no errors).)
  1282. self.assertEqual(my_function('GET', {}), """<form action="" method="post">
  1283. <table>
  1284. <tr><th>Username:</th><td><input type="text" name="username" maxlength="10" /></td></tr>
  1285. <tr><th>Password1:</th><td><input type="password" name="password1" /></td></tr>
  1286. <tr><th>Password2:</th><td><input type="password" name="password2" /></td></tr>
  1287. </table>
  1288. <input type="submit" />
  1289. </form>""")
  1290. # Case 2: POST with erroneous data (a redisplayed form, with errors).)
  1291. self.assertEqual(my_function('POST', {'username': 'this-is-a-long-username', 'password1': 'foo', 'password2': 'bar'}), """<form action="" method="post">
  1292. <table>
  1293. <tr><td colspan="2"><ul class="errorlist"><li>Please make sure your passwords match.</li></ul></td></tr>
  1294. <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>
  1295. <tr><th>Password1:</th><td><input type="password" name="password1" /></td></tr>
  1296. <tr><th>Password2:</th><td><input type="password" name="password2" /></td></tr>
  1297. </table>
  1298. <input type="submit" />
  1299. </form>""")
  1300. # Case 3: POST with valid data (the success message).)
  1301. self.assertEqual(my_function('POST', {'username': 'adrian', 'password1': 'secret', 'password2': 'secret'}), "VALID: {'username': u'adrian', 'password1': u'secret', 'password2': u'secret'}")
  1302. def test_templates_with_forms(self):
  1303. class UserRegistration(Form):
  1304. username = CharField(max_length=10, help_text="Good luck picking a username that doesn't already exist.")
  1305. password1 = CharField(widget=PasswordInput)
  1306. password2 = CharField(widget=PasswordInput)
  1307. def clean(self):
  1308. if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']:
  1309. raise ValidationError(u'Please make sure your passwords match.')
  1310. return self.cleaned_data
  1311. # You have full flexibility in displaying form fields in a template. Just pass a
  1312. # Form instance to the template, and use "dot" access to refer to individual
  1313. # fields. Note, however, that this flexibility comes with the responsibility of
  1314. # displaying all the errors, including any that might not be associated with a
  1315. # particular field.
  1316. t = Template('''<form action="">
  1317. {{ form.username.errors.as_ul }}<p><label>Your username: {{ form.username }}</label></p>
  1318. {{ form.password1.errors.as_ul }}<p><label>Password: {{ form.password1 }}</label></p>
  1319. {{ form.password2.errors.as_ul }}<p><label>Password (again): {{ form.password2 }}</label></p>
  1320. <input type="submit" />
  1321. </form>''')
  1322. self.assertEqual(t.render(Context({'form': UserRegistration(auto_id=False)})), """<form action="">
  1323. <p><label>Your username: <input type="text" name="username" maxlength="10" /></label></p>
  1324. <p><label>Password: <input type="password" name="password1" /></label></p>
  1325. <p><label>Password (again): <input type="password" name="password2" /></label></p>
  1326. <input type="submit" />
  1327. </form>""")
  1328. self.assertEqual(t.render(Context({'form': UserRegistration({'username': 'django'}, auto_id=False)})), """<form action="">
  1329. <p><label>Your username: <input type="text" name="username" value="django" maxlength="10" /></label></p>
  1330. <ul class="errorlist"><li>This field is required.</li></ul><p><label>Password: <input type="password" name="password1" /></label></p>
  1331. <ul class="errorlist"><li>This field is required.</li></ul><p><label>Password (again): <input type="password" name="password2" /></label></p>
  1332. <input type="submit" />
  1333. </form>""")
  1334. # Use form.[field].label to output a field's label. You can specify the label for
  1335. # a field by using the 'label' argument to a Field class. If you don't specify
  1336. # 'label', Django will use the field name with underscores converted to spaces,
  1337. # and the initial letter capitalized.
  1338. t = Template('''<form action="">
  1339. <p><label>{{ form.username.label }}: {{ form.username }}</label></p>
  1340. <p><label>{{ form.password1.label }}: {{ form.password1 }}</label></p>
  1341. <p><label>{{ form.password2.label }}: {{ form.password2 }}</label></p>
  1342. <input type="submit" />
  1343. </form>''')
  1344. self.assertEqual(t.render(Context({'form': UserRegistration(auto_id=False)})), """<form action="">
  1345. <p><label>Username: <input type="text" name="username" maxlength="10" /></label></p>
  1346. <p><label>Password1: <input type="password" name="password1" /></label></p>
  1347. <p><label>Password2: <input type="password" name="password2" /></label></p>
  1348. <input type="submit" />
  1349. </form>""")
  1350. # User form.[field].label_tag to output a field's label with a <label> tag
  1351. # wrapped around it, but *only* if the given field has an "id" attribute.
  1352. # Recall from above that passing the "auto_id" argument to a Form gives each
  1353. # field an "id" attribute.
  1354. t = Template('''<form action="">
  1355. <p>{{ form.username.label_tag }}: {{ form.username }}</p>
  1356. <p>{{ form.password1.label_tag }}: {{ form.password1 }}</p>
  1357. <p>{{ form.password2.label_tag }}: {{ form.password2 }}</p>
  1358. <input type="submit" />
  1359. </form>''')
  1360. self.assertEqual(t.render(Context({'form': UserRegistration(auto_id=False)})), """<form action="">
  1361. <p>Username: <input type="text" name="username" maxlength="10" /></p>
  1362. <p>Password1: <input type="password" name="password1" /></p>
  1363. <p>Password2: <input type="password" name="password2" /></p>
  1364. <input type="submit" />
  1365. </form>""")
  1366. self.assertEqual(t.render(Context({'form': UserRegistration(auto_id='id_%s')})), """<form action="">
  1367. <p><label for="id_username">Username</label>: <input id="id_username" type="text" name="username" maxlength="10" /></p>
  1368. <p><label for="id_password1">Password1</label>: <input type="password" name="password1" id="id_password1" /></p>
  1369. <p><label for="id_password2">Password2</label>: <input type="password" name="password2" id="id_password2" /></p>
  1370. <input type="submit" />
  1371. </form>""")
  1372. # User form.[field].help_text to output a field's help text. If the given field
  1373. # does not have help text, nothing will be output.
  1374. t = Template('''<form action="">
  1375. <p>{{ form.username.label_tag }}: {{ form.username }}<br />{{ form.username.help_text }}</p>
  1376. <p>{{ form.password1.label_tag }}: {{ form.password1 }}</p>
  1377. <p>{{ form.password2.label_tag }}: {{ form.password2 }}</p>
  1378. <input type="submit" />
  1379. </form>''')
  1380. self.assertEqual(t.render(Context({'form': UserRegistration(auto_id=False)})), """<form action="">
  1381. <p>Username: <input type="text" name="username" maxlength="10" /><br />Good luck picking a username that doesn&#39;t already exist.</p>
  1382. <p>Password1: <input type="password" name="password1" /></p>
  1383. <p>Password2: <input type="password" name="password2" /></p>
  1384. <input type="submit" />
  1385. </form>""")
  1386. self.assertEqual(Template('{{ form.password1.help_text }}').render(Context({'form': UserRegistration(auto_id=False)})), u'')
  1387. # The label_tag() method takes an optional attrs argument: a dictionary of HTML
  1388. # attributes to add to the <label> tag.
  1389. f = UserRegistration(auto_id='id_%s')
  1390. form_output = []
  1391. for bf in f:
  1392. form_output.append(bf.label_tag(attrs={'class': 'pretty'}))
  1393. self.assertEqual(form_output, [
  1394. '<label for="id_username" class="pretty">Username</label>',
  1395. '<label for="id_password1" class="pretty">Password1</label>',
  1396. '<label for="id_password2" class="pretty">Password2</label>',
  1397. ])
  1398. # To display the errors that aren't associated with a particular field -- e.g.,
  1399. # the errors caused by Form.clean() -- use {{ form.non_field_errors }} in the
  1400. # template. If used on its own, it is displayed as a <ul> (or an empty string, if
  1401. # the list of errors is empty). You can also use it in {% if %} statements.
  1402. t = Template('''<form action="">
  1403. {{ form.username.errors.as_ul }}<p><label>Your username: {{ form.username }}</label></p>
  1404. {{ form.password1.errors.as_ul }}<p><label>Password: {{ form.password1 }}</label></p>
  1405. {{ form.password2.errors.as_ul }}<p><label>Password (again): {{ form.password2 }}</label></p>
  1406. <input type="submit" />
  1407. </form>''')
  1408. self.assertEqual(t.render(Context({'form': UserRegistration({'username': 'django', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)})), """<form action="">
  1409. <p><label>Your username: <input type="text" name="username" value="django" maxlength="10" /></label></p>
  1410. <p><label>Password: <input type="password" name="password1" /></label></p>
  1411. <p><label>Password (again): <input type="password" name="password2" /></label></p>
  1412. <input type="submit" />
  1413. </form>""")
  1414. t = Template('''<form action="">
  1415. {{ form.non_field_errors }}
  1416. {{ form.username.errors.as_ul }}<p><label>Your username: {{ form.username }}</label></p>
  1417. {{ form.password1.errors.as_ul }}<p><label>Password: {{ form.password1 }}</label></p>
  1418. {{ form.password2.errors.as_ul }}<p><label>Password (again): {{ form.password2 }}</label></p>
  1419. <input type="submit" />
  1420. </form>''')
  1421. self.assertEqual(t.render(Context({'form': UserRegistration({'username': 'django', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)})), """<form action="">
  1422. <ul class="errorlist"><li>Please make sure your passwords match.</li></ul>
  1423. <p><label>Your username: <input type="text" name="username" value="django" maxlength="10" /></label></p>
  1424. <p><label>Password: <input type="password" name="password1" /></label></p>
  1425. <p><label>Password (again): <input type="password" name="password2" /></label></p>
  1426. <input type="submit" />
  1427. </form>""")
  1428. def test_empty_permitted(self):
  1429. # Sometimes (pretty much in formsets) we want to allow a form to pass validation
  1430. # if it is completely empty. We can accomplish this by using the empty_permitted
  1431. # agrument to a form constructor.
  1432. class SongForm(Form):
  1433. artist = CharField()
  1434. name = CharField()
  1435. # First let's show what happens id empty_permitted=False (the default):
  1436. data = {'artist': '', 'song': ''}
  1437. form = SongForm(data, empty_permitted=False)
  1438. self.assertFalse(form.is_valid())
  1439. self.assertEqual(form.errors, {'name': [u'This field is required.'], 'artist': [u'This field is required.']})
  1440. try:
  1441. form.cleaned_data
  1442. self.fail('Attempts to access cleaned_data when validation fails should fail.')
  1443. except AttributeError:
  1444. pass
  1445. # Now let's show what happens when empty_permitted=True and the form is empty.
  1446. form = SongForm(data, empty_permitted=True)
  1447. self.assertTrue(form.is_valid())
  1448. self.assertEqual(form.errors, {})
  1449. self.assertEqual(form.cleaned_data, {})
  1450. # But if we fill in data for one of the fields, the form is no longer empty and
  1451. # the whole thing must pass validation.
  1452. data = {'artist': 'The Doors', 'song': ''}
  1453. form = SongForm(data, empty_permitted=False)
  1454. self.assertFalse(form.is_valid())
  1455. self.assertEqual(form.errors, {'name': [u'This field is required.']})
  1456. try:
  1457. form.cleaned_data
  1458. self.fail('Attempts to access cleaned_data when validation fails should fail.')
  1459. except AttributeError:
  1460. pass
  1461. # If a field is not given in the data then None is returned for its data. Lets
  1462. # make sure that when checking for empty_permitted that None is treated
  1463. # accordingly.
  1464. data = {'artist': None, 'song': ''}
  1465. form = SongForm(data, empty_permitted=True)
  1466. self.assertTrue(form.is_valid())
  1467. # However, we *really* need to be sure we are checking for None as any data in
  1468. # initial that returns False on a boolean call needs to be treated literally.
  1469. class PriceForm(Form):
  1470. amount = FloatField()
  1471. qty = IntegerField()
  1472. data = {'amount': '0.0', 'qty': ''}
  1473. form = PriceForm(data, initial={'amount': 0.0}, empty_permitted=True)
  1474. self.assertTrue(form.is_valid())
  1475. def test_extracting_hidden_and_visible(self):
  1476. class SongForm(Form):
  1477. token = CharField(widget=HiddenInput)
  1478. artist = CharField()
  1479. name = CharField()
  1480. form = SongForm()
  1481. self.assertEqual([f.name for f in form.hidden_fields()], ['token'])
  1482. self.assertEqual([f.name for f in form.visible_fields()], ['artist', 'name'])
  1483. def test_hidden_initial_gets_id(self):
  1484. class MyForm(Form):
  1485. field1 = CharField(max_length=50, show_hidden_initial=True)
  1486. 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>')
  1487. def test_error_html_required_html_classes(self):
  1488. class Person(Form):
  1489. name = CharField()
  1490. is_cool = NullBooleanField()
  1491. email = EmailField(required=False)
  1492. age = IntegerField()
  1493. p = Person({})
  1494. p.error_css_class = 'error'
  1495. p.required_css_class = 'required'
  1496. 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>
  1497. <li class="required"><label for="id_is_cool">Is cool:</label> <select name="is_cool" id="id_is_cool">
  1498. <option value="1" selected="selected">Unknown</option>
  1499. <option value="2">Yes</option>
  1500. <option value="3">No</option>
  1501. </select></li>
  1502. <li><label for="id_email">Email:</label> <input type="text" name="email" id="id_email" /></li>
  1503. <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>""")
  1504. self.assertEqual(p.as_p(), """<ul class="errorlist"><li>This field is required.</li></ul>
  1505. <p class="required error"><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" /></p>
  1506. <p class="required"><label for="id_is_cool">Is cool:</label> <select name="is_cool" id="id_is_cool">
  1507. <option value="1" selected="selected">Unknown</option>
  1508. <option value="2">Yes</option>
  1509. <option value="3">No</option>
  1510. </select></p>
  1511. <p><label for="id_email">Email:</label> <input type="text" name="email" id="id_email" /></p>
  1512. <ul class="errorlist"><li>This field is required.</li></ul>
  1513. <p class="required error"><label for="id_age">Age:</label> <input type="text" name="age" id="id_age" /></p>""")
  1514. 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>
  1515. <tr class="required"><th><label for="id_is_cool">Is cool:</label></th><td><select name="is_cool" id="id_is_cool">
  1516. <option value="1" selected="selected">Unknown</option>
  1517. <option value="2">Yes</option>
  1518. <option value="3">No</option>
  1519. </select></td></tr>
  1520. <tr><th><label for="id_email">Email:</label></th><td><input type="text" name="email" id="id_email" /></td></tr>
  1521. <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>""")
  1522. def test_label_split_datetime_not_displayed(self):
  1523. class EventForm(Form):
  1524. happened_at = SplitDateTimeField(widget=widgets.SplitHiddenDateTimeWidget)
  1525. form = EventForm()
  1526. 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" />')