test_forms.py 167 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. import copy
  4. import datetime
  5. import json
  6. import uuid
  7. from django.core.exceptions import NON_FIELD_ERRORS
  8. from django.core.files.uploadedfile import SimpleUploadedFile
  9. from django.core.validators import MaxValueValidator, RegexValidator
  10. from django.forms import (
  11. BooleanField, CharField, CheckboxSelectMultiple, ChoiceField, DateField,
  12. DateTimeField, EmailField, FileField, FloatField, Form, HiddenInput,
  13. ImageField, IntegerField, MultipleChoiceField, MultipleHiddenInput,
  14. MultiValueField, NullBooleanField, PasswordInput, RadioSelect, Select,
  15. SplitDateTimeField, SplitHiddenDateTimeWidget, Textarea, TextInput,
  16. TimeField, ValidationError, forms,
  17. )
  18. from django.forms.renderers import DjangoTemplates, get_default_renderer
  19. from django.forms.utils import ErrorList
  20. from django.http import QueryDict
  21. from django.template import Context, Template
  22. from django.test import SimpleTestCase
  23. from django.test.utils import str_prefix
  24. from django.utils.datastructures import MultiValueDict
  25. from django.utils.encoding import force_text, python_2_unicode_compatible
  26. from django.utils.html import format_html
  27. from django.utils.safestring import SafeData, mark_safe
  28. class Person(Form):
  29. first_name = CharField()
  30. last_name = CharField()
  31. birthday = DateField()
  32. class PersonNew(Form):
  33. first_name = CharField(widget=TextInput(attrs={'id': 'first_name_id'}))
  34. last_name = CharField()
  35. birthday = DateField()
  36. class MultiValueDictLike(dict):
  37. def getlist(self, key):
  38. return [self[key]]
  39. class FormsTestCase(SimpleTestCase):
  40. # A Form is a collection of Fields. It knows how to validate a set of data and it
  41. # knows how to render itself in a couple of default ways (e.g., an HTML table).
  42. # You can pass it data in __init__(), as a dictionary.
  43. def test_form(self):
  44. # Pass a dictionary to a Form's __init__().
  45. p = Person({'first_name': 'John', 'last_name': 'Lennon', 'birthday': '1940-10-9'})
  46. self.assertTrue(p.is_bound)
  47. self.assertEqual(p.errors, {})
  48. self.assertTrue(p.is_valid())
  49. self.assertHTMLEqual(p.errors.as_ul(), '')
  50. self.assertEqual(p.errors.as_text(), '')
  51. self.assertEqual(p.cleaned_data["first_name"], 'John')
  52. self.assertEqual(p.cleaned_data["last_name"], 'Lennon')
  53. self.assertEqual(p.cleaned_data["birthday"], datetime.date(1940, 10, 9))
  54. self.assertHTMLEqual(
  55. str(p['first_name']),
  56. '<input type="text" name="first_name" value="John" id="id_first_name" required />'
  57. )
  58. self.assertHTMLEqual(
  59. str(p['last_name']),
  60. '<input type="text" name="last_name" value="Lennon" id="id_last_name" required />'
  61. )
  62. self.assertHTMLEqual(
  63. str(p['birthday']),
  64. '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" required />'
  65. )
  66. msg = "Key 'nonexistentfield' not found in 'Person'. Choices are: birthday, first_name, last_name."
  67. with self.assertRaisesMessage(KeyError, msg):
  68. p['nonexistentfield']
  69. form_output = []
  70. for boundfield in p:
  71. form_output.append(str(boundfield))
  72. self.assertHTMLEqual(
  73. '\n'.join(form_output),
  74. """<input type="text" name="first_name" value="John" id="id_first_name" required />
  75. <input type="text" name="last_name" value="Lennon" id="id_last_name" required />
  76. <input type="text" name="birthday" value="1940-10-9" id="id_birthday" required />"""
  77. )
  78. form_output = []
  79. for boundfield in p:
  80. form_output.append([boundfield.label, boundfield.data])
  81. self.assertEqual(form_output, [
  82. ['First name', 'John'],
  83. ['Last name', 'Lennon'],
  84. ['Birthday', '1940-10-9']
  85. ])
  86. self.assertHTMLEqual(
  87. str(p),
  88. """<tr><th><label for="id_first_name">First name:</label></th><td>
  89. <input type="text" name="first_name" value="John" id="id_first_name" required /></td></tr>
  90. <tr><th><label for="id_last_name">Last name:</label></th><td>
  91. <input type="text" name="last_name" value="Lennon" id="id_last_name" required /></td></tr>
  92. <tr><th><label for="id_birthday">Birthday:</label></th><td>
  93. <input type="text" name="birthday" value="1940-10-9" id="id_birthday" required /></td></tr>"""
  94. )
  95. def test_empty_dict(self):
  96. # Empty dictionaries are valid, too.
  97. p = Person({})
  98. self.assertTrue(p.is_bound)
  99. self.assertEqual(p.errors['first_name'], ['This field is required.'])
  100. self.assertEqual(p.errors['last_name'], ['This field is required.'])
  101. self.assertEqual(p.errors['birthday'], ['This field is required.'])
  102. self.assertFalse(p.is_valid())
  103. self.assertEqual(p.cleaned_data, {})
  104. self.assertHTMLEqual(
  105. str(p),
  106. """<tr><th><label for="id_first_name">First name:</label></th><td>
  107. <ul class="errorlist"><li>This field is required.</li></ul>
  108. <input type="text" name="first_name" id="id_first_name" required /></td></tr>
  109. <tr><th><label for="id_last_name">Last name:</label></th>
  110. <td><ul class="errorlist"><li>This field is required.</li></ul>
  111. <input type="text" name="last_name" id="id_last_name" required /></td></tr>
  112. <tr><th><label for="id_birthday">Birthday:</label></th><td>
  113. <ul class="errorlist"><li>This field is required.</li></ul>
  114. <input type="text" name="birthday" id="id_birthday" required /></td></tr>"""
  115. )
  116. self.assertHTMLEqual(
  117. p.as_table(),
  118. """<tr><th><label for="id_first_name">First name:</label></th><td>
  119. <ul class="errorlist"><li>This field is required.</li></ul>
  120. <input type="text" name="first_name" id="id_first_name" required /></td></tr>
  121. <tr><th><label for="id_last_name">Last name:</label></th>
  122. <td><ul class="errorlist"><li>This field is required.</li></ul>
  123. <input type="text" name="last_name" id="id_last_name" required /></td></tr>
  124. <tr><th><label for="id_birthday">Birthday:</label></th>
  125. <td><ul class="errorlist"><li>This field is required.</li></ul>
  126. <input type="text" name="birthday" id="id_birthday" required /></td></tr>"""
  127. )
  128. self.assertHTMLEqual(
  129. p.as_ul(),
  130. """<li><ul class="errorlist"><li>This field is required.</li></ul>
  131. <label for="id_first_name">First name:</label>
  132. <input type="text" name="first_name" id="id_first_name" required /></li>
  133. <li><ul class="errorlist"><li>This field is required.</li></ul>
  134. <label for="id_last_name">Last name:</label>
  135. <input type="text" name="last_name" id="id_last_name" required /></li>
  136. <li><ul class="errorlist"><li>This field is required.</li></ul>
  137. <label for="id_birthday">Birthday:</label>
  138. <input type="text" name="birthday" id="id_birthday" required /></li>"""
  139. )
  140. self.assertHTMLEqual(
  141. p.as_p(),
  142. """<ul class="errorlist"><li>This field is required.</li></ul>
  143. <p><label for="id_first_name">First name:</label>
  144. <input type="text" name="first_name" id="id_first_name" required /></p>
  145. <ul class="errorlist"><li>This field is required.</li></ul>
  146. <p><label for="id_last_name">Last name:</label>
  147. <input type="text" name="last_name" id="id_last_name" required /></p>
  148. <ul class="errorlist"><li>This field is required.</li></ul>
  149. <p><label for="id_birthday">Birthday:</label>
  150. <input type="text" name="birthday" id="id_birthday" required /></p>"""
  151. )
  152. def test_unbound_form(self):
  153. # If you don't pass any values to the Form's __init__(), or if you pass None,
  154. # the Form will be considered unbound and won't do any validation. Form.errors
  155. # will be an empty dictionary *but* Form.is_valid() will return False.
  156. p = Person()
  157. self.assertFalse(p.is_bound)
  158. self.assertEqual(p.errors, {})
  159. self.assertFalse(p.is_valid())
  160. with self.assertRaises(AttributeError):
  161. p.cleaned_data
  162. self.assertHTMLEqual(
  163. str(p),
  164. """<tr><th><label for="id_first_name">First name:</label></th><td>
  165. <input type="text" name="first_name" id="id_first_name" required /></td></tr>
  166. <tr><th><label for="id_last_name">Last name:</label></th><td>
  167. <input type="text" name="last_name" id="id_last_name" required /></td></tr>
  168. <tr><th><label for="id_birthday">Birthday:</label></th><td>
  169. <input type="text" name="birthday" id="id_birthday" required /></td></tr>"""
  170. )
  171. self.assertHTMLEqual(
  172. p.as_table(),
  173. """<tr><th><label for="id_first_name">First name:</label></th><td>
  174. <input type="text" name="first_name" id="id_first_name" required /></td></tr>
  175. <tr><th><label for="id_last_name">Last name:</label></th><td>
  176. <input type="text" name="last_name" id="id_last_name" required /></td></tr>
  177. <tr><th><label for="id_birthday">Birthday:</label></th><td>
  178. <input type="text" name="birthday" id="id_birthday" required /></td></tr>"""
  179. )
  180. self.assertHTMLEqual(
  181. p.as_ul(),
  182. """<li><label for="id_first_name">First name:</label>
  183. <input type="text" name="first_name" id="id_first_name" required /></li>
  184. <li><label for="id_last_name">Last name:</label>
  185. <input type="text" name="last_name" id="id_last_name" required /></li>
  186. <li><label for="id_birthday">Birthday:</label>
  187. <input type="text" name="birthday" id="id_birthday" required /></li>"""
  188. )
  189. self.assertHTMLEqual(
  190. p.as_p(),
  191. """<p><label for="id_first_name">First name:</label>
  192. <input type="text" name="first_name" id="id_first_name" required /></p>
  193. <p><label for="id_last_name">Last name:</label>
  194. <input type="text" name="last_name" id="id_last_name" required /></p>
  195. <p><label for="id_birthday">Birthday:</label>
  196. <input type="text" name="birthday" id="id_birthday" required /></p>"""
  197. )
  198. def test_unicode_values(self):
  199. # Unicode values are handled properly.
  200. p = Person({
  201. 'first_name': 'John',
  202. 'last_name': '\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111',
  203. 'birthday': '1940-10-9'
  204. })
  205. self.assertHTMLEqual(
  206. p.as_table(),
  207. '<tr><th><label for="id_first_name">First name:</label></th><td>'
  208. '<input type="text" name="first_name" value="John" id="id_first_name" required /></td></tr>\n'
  209. '<tr><th><label for="id_last_name">Last name:</label>'
  210. '</th><td><input type="text" name="last_name" '
  211. 'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111"'
  212. 'id="id_last_name" required /></td></tr>\n'
  213. '<tr><th><label for="id_birthday">Birthday:</label></th><td>'
  214. '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" required /></td></tr>'
  215. )
  216. self.assertHTMLEqual(
  217. p.as_ul(),
  218. '<li><label for="id_first_name">First name:</label> '
  219. '<input type="text" name="first_name" value="John" id="id_first_name" required /></li>\n'
  220. '<li><label for="id_last_name">Last name:</label> '
  221. '<input type="text" name="last_name" '
  222. 'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" id="id_last_name" required /></li>\n'
  223. '<li><label for="id_birthday">Birthday:</label> '
  224. '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" required /></li>'
  225. )
  226. self.assertHTMLEqual(
  227. p.as_p(),
  228. '<p><label for="id_first_name">First name:</label> '
  229. '<input type="text" name="first_name" value="John" id="id_first_name" required /></p>\n'
  230. '<p><label for="id_last_name">Last name:</label> '
  231. '<input type="text" name="last_name" '
  232. 'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" id="id_last_name" required /></p>\n'
  233. '<p><label for="id_birthday">Birthday:</label> '
  234. '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" required /></p>'
  235. )
  236. p = Person({'last_name': 'Lennon'})
  237. self.assertEqual(p.errors['first_name'], ['This field is required.'])
  238. self.assertEqual(p.errors['birthday'], ['This field is required.'])
  239. self.assertFalse(p.is_valid())
  240. self.assertDictEqual(
  241. p.errors,
  242. {'birthday': ['This field is required.'], 'first_name': ['This field is required.']}
  243. )
  244. self.assertEqual(p.cleaned_data, {'last_name': 'Lennon'})
  245. self.assertEqual(p['first_name'].errors, ['This field is required.'])
  246. self.assertHTMLEqual(
  247. p['first_name'].errors.as_ul(),
  248. '<ul class="errorlist"><li>This field is required.</li></ul>'
  249. )
  250. self.assertEqual(p['first_name'].errors.as_text(), '* This field is required.')
  251. p = Person()
  252. self.assertHTMLEqual(
  253. str(p['first_name']),
  254. '<input type="text" name="first_name" id="id_first_name" required />',
  255. )
  256. self.assertHTMLEqual(str(p['last_name']), '<input type="text" name="last_name" id="id_last_name" required />')
  257. self.assertHTMLEqual(str(p['birthday']), '<input type="text" name="birthday" id="id_birthday" required />')
  258. def test_cleaned_data_only_fields(self):
  259. # cleaned_data will always *only* contain a key for fields defined in the
  260. # Form, even if you pass extra data when you define the Form. In this
  261. # example, we pass a bunch of extra fields to the form constructor,
  262. # but cleaned_data contains only the form's fields.
  263. data = {
  264. 'first_name': 'John',
  265. 'last_name': 'Lennon',
  266. 'birthday': '1940-10-9',
  267. 'extra1': 'hello',
  268. 'extra2': 'hello',
  269. }
  270. p = Person(data)
  271. self.assertTrue(p.is_valid())
  272. self.assertEqual(p.cleaned_data['first_name'], 'John')
  273. self.assertEqual(p.cleaned_data['last_name'], 'Lennon')
  274. self.assertEqual(p.cleaned_data['birthday'], datetime.date(1940, 10, 9))
  275. def test_optional_data(self):
  276. # cleaned_data will include a key and value for *all* fields defined in the Form,
  277. # even if the Form's data didn't include a value for fields that are not
  278. # required. In this example, the data dictionary doesn't include a value for the
  279. # "nick_name" field, but cleaned_data includes it. For CharFields, it's set to the
  280. # empty string.
  281. class OptionalPersonForm(Form):
  282. first_name = CharField()
  283. last_name = CharField()
  284. nick_name = CharField(required=False)
  285. data = {'first_name': 'John', 'last_name': 'Lennon'}
  286. f = OptionalPersonForm(data)
  287. self.assertTrue(f.is_valid())
  288. self.assertEqual(f.cleaned_data['nick_name'], '')
  289. self.assertEqual(f.cleaned_data['first_name'], 'John')
  290. self.assertEqual(f.cleaned_data['last_name'], 'Lennon')
  291. # For DateFields, it's set to None.
  292. class OptionalPersonForm(Form):
  293. first_name = CharField()
  294. last_name = CharField()
  295. birth_date = DateField(required=False)
  296. data = {'first_name': 'John', 'last_name': 'Lennon'}
  297. f = OptionalPersonForm(data)
  298. self.assertTrue(f.is_valid())
  299. self.assertIsNone(f.cleaned_data['birth_date'])
  300. self.assertEqual(f.cleaned_data['first_name'], 'John')
  301. self.assertEqual(f.cleaned_data['last_name'], 'Lennon')
  302. def test_auto_id(self):
  303. # "auto_id" tells the Form to add an "id" attribute to each form element.
  304. # If it's a string that contains '%s', Django will use that as a format string
  305. # into which the field's name will be inserted. It will also put a <label> around
  306. # the human-readable labels for a field.
  307. p = Person(auto_id='%s_id')
  308. self.assertHTMLEqual(
  309. p.as_table(),
  310. """<tr><th><label for="first_name_id">First name:</label></th><td>
  311. <input type="text" name="first_name" id="first_name_id" required /></td></tr>
  312. <tr><th><label for="last_name_id">Last name:</label></th><td>
  313. <input type="text" name="last_name" id="last_name_id" required /></td></tr>
  314. <tr><th><label for="birthday_id">Birthday:</label></th><td>
  315. <input type="text" name="birthday" id="birthday_id" required /></td></tr>"""
  316. )
  317. self.assertHTMLEqual(
  318. p.as_ul(),
  319. """<li><label for="first_name_id">First name:</label>
  320. <input type="text" name="first_name" id="first_name_id" required /></li>
  321. <li><label for="last_name_id">Last name:</label>
  322. <input type="text" name="last_name" id="last_name_id" required /></li>
  323. <li><label for="birthday_id">Birthday:</label>
  324. <input type="text" name="birthday" id="birthday_id" required /></li>"""
  325. )
  326. self.assertHTMLEqual(
  327. p.as_p(),
  328. """<p><label for="first_name_id">First name:</label>
  329. <input type="text" name="first_name" id="first_name_id" required /></p>
  330. <p><label for="last_name_id">Last name:</label>
  331. <input type="text" name="last_name" id="last_name_id" required /></p>
  332. <p><label for="birthday_id">Birthday:</label>
  333. <input type="text" name="birthday" id="birthday_id" required /></p>"""
  334. )
  335. def test_auto_id_true(self):
  336. # If auto_id is any True value whose str() does not contain '%s', the "id"
  337. # attribute will be the name of the field.
  338. p = Person(auto_id=True)
  339. self.assertHTMLEqual(
  340. p.as_ul(),
  341. """<li><label for="first_name">First name:</label>
  342. <input type="text" name="first_name" id="first_name" required /></li>
  343. <li><label for="last_name">Last name:</label>
  344. <input type="text" name="last_name" id="last_name" required /></li>
  345. <li><label for="birthday">Birthday:</label>
  346. <input type="text" name="birthday" id="birthday" required /></li>"""
  347. )
  348. def test_auto_id_false(self):
  349. # If auto_id is any False value, an "id" attribute won't be output unless it
  350. # was manually entered.
  351. p = Person(auto_id=False)
  352. self.assertHTMLEqual(
  353. p.as_ul(),
  354. """<li>First name: <input type="text" name="first_name" required /></li>
  355. <li>Last name: <input type="text" name="last_name" required /></li>
  356. <li>Birthday: <input type="text" name="birthday" required /></li>"""
  357. )
  358. def test_id_on_field(self):
  359. # In this example, auto_id is False, but the "id" attribute for the "first_name"
  360. # field is given. Also note that field gets a <label>, while the others don't.
  361. p = PersonNew(auto_id=False)
  362. self.assertHTMLEqual(
  363. p.as_ul(),
  364. """<li><label for="first_name_id">First name:</label>
  365. <input type="text" id="first_name_id" name="first_name" required /></li>
  366. <li>Last name: <input type="text" name="last_name" required /></li>
  367. <li>Birthday: <input type="text" name="birthday" required /></li>"""
  368. )
  369. def test_auto_id_on_form_and_field(self):
  370. # If the "id" attribute is specified in the Form and auto_id is True, the "id"
  371. # attribute in the Form gets precedence.
  372. p = PersonNew(auto_id=True)
  373. self.assertHTMLEqual(
  374. p.as_ul(),
  375. """<li><label for="first_name_id">First name:</label>
  376. <input type="text" id="first_name_id" name="first_name" required /></li>
  377. <li><label for="last_name">Last name:</label>
  378. <input type="text" name="last_name" id="last_name" required /></li>
  379. <li><label for="birthday">Birthday:</label>
  380. <input type="text" name="birthday" id="birthday" required /></li>"""
  381. )
  382. def test_various_boolean_values(self):
  383. class SignupForm(Form):
  384. email = EmailField()
  385. get_spam = BooleanField()
  386. f = SignupForm(auto_id=False)
  387. self.assertHTMLEqual(str(f['email']), '<input type="email" name="email" required />')
  388. self.assertHTMLEqual(str(f['get_spam']), '<input type="checkbox" name="get_spam" required />')
  389. f = SignupForm({'email': 'test@example.com', 'get_spam': True}, auto_id=False)
  390. self.assertHTMLEqual(str(f['email']), '<input type="email" name="email" value="test@example.com" required />')
  391. self.assertHTMLEqual(
  392. str(f['get_spam']),
  393. '<input checked type="checkbox" name="get_spam" required />',
  394. )
  395. # 'True' or 'true' should be rendered without a value attribute
  396. f = SignupForm({'email': 'test@example.com', 'get_spam': 'True'}, auto_id=False)
  397. self.assertHTMLEqual(
  398. str(f['get_spam']),
  399. '<input checked type="checkbox" name="get_spam" required />',
  400. )
  401. f = SignupForm({'email': 'test@example.com', 'get_spam': 'true'}, auto_id=False)
  402. self.assertHTMLEqual(
  403. str(f['get_spam']), '<input checked type="checkbox" name="get_spam" required />')
  404. # A value of 'False' or 'false' should be rendered unchecked
  405. f = SignupForm({'email': 'test@example.com', 'get_spam': 'False'}, auto_id=False)
  406. self.assertHTMLEqual(str(f['get_spam']), '<input type="checkbox" name="get_spam" required />')
  407. f = SignupForm({'email': 'test@example.com', 'get_spam': 'false'}, auto_id=False)
  408. self.assertHTMLEqual(str(f['get_spam']), '<input type="checkbox" name="get_spam" required />')
  409. # A value of '0' should be interpreted as a True value (#16820)
  410. f = SignupForm({'email': 'test@example.com', 'get_spam': '0'})
  411. self.assertTrue(f.is_valid())
  412. self.assertTrue(f.cleaned_data.get('get_spam'))
  413. def test_widget_output(self):
  414. # Any Field can have a Widget class passed to its constructor:
  415. class ContactForm(Form):
  416. subject = CharField()
  417. message = CharField(widget=Textarea)
  418. f = ContactForm(auto_id=False)
  419. self.assertHTMLEqual(str(f['subject']), '<input type="text" name="subject" required />')
  420. self.assertHTMLEqual(str(f['message']), '<textarea name="message" rows="10" cols="40" required></textarea>')
  421. # as_textarea(), as_text() and as_hidden() are shortcuts for changing the output
  422. # widget type:
  423. self.assertHTMLEqual(
  424. f['subject'].as_textarea(),
  425. '<textarea name="subject" rows="10" cols="40" required></textarea>',
  426. )
  427. self.assertHTMLEqual(f['message'].as_text(), '<input type="text" name="message" required />')
  428. self.assertHTMLEqual(f['message'].as_hidden(), '<input type="hidden" name="message" />')
  429. # The 'widget' parameter to a Field can also be an instance:
  430. class ContactForm(Form):
  431. subject = CharField()
  432. message = CharField(widget=Textarea(attrs={'rows': 80, 'cols': 20}))
  433. f = ContactForm(auto_id=False)
  434. self.assertHTMLEqual(str(f['message']), '<textarea name="message" rows="80" cols="20" required></textarea>')
  435. # Instance-level attrs are *not* carried over to as_textarea(), as_text() and
  436. # as_hidden():
  437. self.assertHTMLEqual(f['message'].as_text(), '<input type="text" name="message" required />')
  438. f = ContactForm({'subject': 'Hello', 'message': 'I love you.'}, auto_id=False)
  439. self.assertHTMLEqual(
  440. f['subject'].as_textarea(),
  441. '<textarea rows="10" cols="40" name="subject" required>Hello</textarea>'
  442. )
  443. self.assertHTMLEqual(
  444. f['message'].as_text(),
  445. '<input type="text" name="message" value="I love you." required />',
  446. )
  447. self.assertHTMLEqual(f['message'].as_hidden(), '<input type="hidden" name="message" value="I love you." />')
  448. def test_forms_with_choices(self):
  449. # For a form with a <select>, use ChoiceField:
  450. class FrameworkForm(Form):
  451. name = CharField()
  452. language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')])
  453. f = FrameworkForm(auto_id=False)
  454. self.assertHTMLEqual(str(f['language']), """<select name="language" required>
  455. <option value="P">Python</option>
  456. <option value="J">Java</option>
  457. </select>""")
  458. f = FrameworkForm({'name': 'Django', 'language': 'P'}, auto_id=False)
  459. self.assertHTMLEqual(str(f['language']), """<select name="language" required>
  460. <option value="P" selected>Python</option>
  461. <option value="J">Java</option>
  462. </select>""")
  463. # A subtlety: If one of the choices' value is the empty string and the form is
  464. # unbound, then the <option> for the empty-string choice will get selected.
  465. class FrameworkForm(Form):
  466. name = CharField()
  467. language = ChoiceField(choices=[('', '------'), ('P', 'Python'), ('J', 'Java')])
  468. f = FrameworkForm(auto_id=False)
  469. self.assertHTMLEqual(str(f['language']), """<select name="language" required>
  470. <option value="" selected>------</option>
  471. <option value="P">Python</option>
  472. <option value="J">Java</option>
  473. </select>""")
  474. # You can specify widget attributes in the Widget constructor.
  475. class FrameworkForm(Form):
  476. name = CharField()
  477. language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')], widget=Select(attrs={'class': 'foo'}))
  478. f = FrameworkForm(auto_id=False)
  479. self.assertHTMLEqual(str(f['language']), """<select class="foo" name="language" required>
  480. <option value="P">Python</option>
  481. <option value="J">Java</option>
  482. </select>""")
  483. f = FrameworkForm({'name': 'Django', 'language': 'P'}, auto_id=False)
  484. self.assertHTMLEqual(str(f['language']), """<select class="foo" name="language" required>
  485. <option value="P" selected>Python</option>
  486. <option value="J">Java</option>
  487. </select>""")
  488. # When passing a custom widget instance to ChoiceField, note that setting
  489. # 'choices' on the widget is meaningless. The widget will use the choices
  490. # defined on the Field, not the ones defined on the Widget.
  491. class FrameworkForm(Form):
  492. name = CharField()
  493. language = ChoiceField(
  494. choices=[('P', 'Python'), ('J', 'Java')],
  495. widget=Select(choices=[('R', 'Ruby'), ('P', 'Perl')], attrs={'class': 'foo'}),
  496. )
  497. f = FrameworkForm(auto_id=False)
  498. self.assertHTMLEqual(str(f['language']), """<select class="foo" name="language" required>
  499. <option value="P">Python</option>
  500. <option value="J">Java</option>
  501. </select>""")
  502. f = FrameworkForm({'name': 'Django', 'language': 'P'}, auto_id=False)
  503. self.assertHTMLEqual(str(f['language']), """<select class="foo" name="language" required>
  504. <option value="P" selected>Python</option>
  505. <option value="J">Java</option>
  506. </select>""")
  507. # You can set a ChoiceField's choices after the fact.
  508. class FrameworkForm(Form):
  509. name = CharField()
  510. language = ChoiceField()
  511. f = FrameworkForm(auto_id=False)
  512. self.assertHTMLEqual(str(f['language']), """<select name="language" required>
  513. </select>""")
  514. f.fields['language'].choices = [('P', 'Python'), ('J', 'Java')]
  515. self.assertHTMLEqual(str(f['language']), """<select name="language" required>
  516. <option value="P">Python</option>
  517. <option value="J">Java</option>
  518. </select>""")
  519. def test_forms_with_radio(self):
  520. # Add widget=RadioSelect to use that widget with a ChoiceField.
  521. class FrameworkForm(Form):
  522. name = CharField()
  523. language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')], widget=RadioSelect)
  524. f = FrameworkForm(auto_id=False)
  525. self.assertHTMLEqual(str(f['language']), """<ul>
  526. <li><label><input type="radio" name="language" value="P" required /> Python</label></li>
  527. <li><label><input type="radio" name="language" value="J" required /> Java</label></li>
  528. </ul>""")
  529. self.assertHTMLEqual(f.as_table(), """<tr><th>Name:</th><td><input type="text" name="name" required /></td></tr>
  530. <tr><th>Language:</th><td><ul>
  531. <li><label><input type="radio" name="language" value="P" required /> Python</label></li>
  532. <li><label><input type="radio" name="language" value="J" required /> Java</label></li>
  533. </ul></td></tr>""")
  534. self.assertHTMLEqual(f.as_ul(), """<li>Name: <input type="text" name="name" required /></li>
  535. <li>Language: <ul>
  536. <li><label><input type="radio" name="language" value="P" required /> Python</label></li>
  537. <li><label><input type="radio" name="language" value="J" required /> Java</label></li>
  538. </ul></li>""")
  539. # Regarding auto_id and <label>, RadioSelect is a special case. Each radio button
  540. # gets a distinct ID, formed by appending an underscore plus the button's
  541. # zero-based index.
  542. f = FrameworkForm(auto_id='id_%s')
  543. self.assertHTMLEqual(
  544. str(f['language']),
  545. """<ul id="id_language">
  546. <li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" required />
  547. Python</label></li>
  548. <li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" required />
  549. Java</label></li>
  550. </ul>"""
  551. )
  552. # When RadioSelect is used with auto_id, and the whole form is printed using
  553. # either as_table() or as_ul(), the label for the RadioSelect will point to the
  554. # ID of the *first* radio button.
  555. self.assertHTMLEqual(
  556. f.as_table(),
  557. """<tr><th><label for="id_name">Name:</label></th><td><input type="text" name="name" id="id_name" required /></td></tr>
  558. <tr><th><label for="id_language_0">Language:</label></th><td><ul id="id_language">
  559. <li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" required />
  560. Python</label></li>
  561. <li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" required />
  562. Java</label></li>
  563. </ul></td></tr>"""
  564. )
  565. self.assertHTMLEqual(
  566. f.as_ul(),
  567. """<li><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" required /></li>
  568. <li><label for="id_language_0">Language:</label> <ul id="id_language">
  569. <li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" required />
  570. Python</label></li>
  571. <li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" required />
  572. Java</label></li>
  573. </ul></li>"""
  574. )
  575. self.assertHTMLEqual(
  576. f.as_p(),
  577. """<p><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" required /></p>
  578. <p><label for="id_language_0">Language:</label> <ul id="id_language">
  579. <li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" required />
  580. Python</label></li>
  581. <li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" required />
  582. Java</label></li>
  583. </ul></p>"""
  584. )
  585. # Test iterating on individual radios in a template
  586. t = Template('{% for radio in form.language %}<div class="myradio">{{ radio }}</div>{% endfor %}')
  587. self.assertHTMLEqual(
  588. t.render(Context({'form': f})),
  589. """<div class="myradio"><label for="id_language_0">
  590. <input id="id_language_0" name="language" type="radio" value="P" required /> Python</label></div>
  591. <div class="myradio"><label for="id_language_1">
  592. <input id="id_language_1" name="language" type="radio" value="J" required /> Java</label></div>"""
  593. )
  594. def test_form_with_iterable_boundfield(self):
  595. class BeatleForm(Form):
  596. name = ChoiceField(
  597. choices=[('john', 'John'), ('paul', 'Paul'), ('george', 'George'), ('ringo', 'Ringo')],
  598. widget=RadioSelect,
  599. )
  600. f = BeatleForm(auto_id=False)
  601. self.assertHTMLEqual(
  602. '\n'.join(str(bf) for bf in f['name']),
  603. """<label><input type="radio" name="name" value="john" required /> John</label>
  604. <label><input type="radio" name="name" value="paul" required /> Paul</label>
  605. <label><input type="radio" name="name" value="george" required /> George</label>
  606. <label><input type="radio" name="name" value="ringo" required /> Ringo</label>"""
  607. )
  608. self.assertHTMLEqual(
  609. '\n'.join('<div>%s</div>' % bf for bf in f['name']),
  610. """<div><label><input type="radio" name="name" value="john" required /> John</label></div>
  611. <div><label><input type="radio" name="name" value="paul" required /> Paul</label></div>
  612. <div><label><input type="radio" name="name" value="george" required /> George</label></div>
  613. <div><label><input type="radio" name="name" value="ringo" required /> Ringo</label></div>"""
  614. )
  615. def test_form_with_iterable_boundfield_id(self):
  616. class BeatleForm(Form):
  617. name = ChoiceField(
  618. choices=[('john', 'John'), ('paul', 'Paul'), ('george', 'George'), ('ringo', 'Ringo')],
  619. widget=RadioSelect,
  620. )
  621. fields = list(BeatleForm()['name'])
  622. self.assertEqual(len(fields), 4)
  623. self.assertEqual(fields[0].id_for_label, 'id_name_0')
  624. self.assertEqual(fields[0].choice_label, 'John')
  625. self.assertHTMLEqual(
  626. fields[0].tag(),
  627. '<input type="radio" name="name" value="john" id="id_name_0" required />'
  628. )
  629. self.assertHTMLEqual(
  630. str(fields[0]),
  631. '<label for="id_name_0"><input type="radio" name="name" '
  632. 'value="john" id="id_name_0" required /> John</label>'
  633. )
  634. self.assertEqual(fields[1].id_for_label, 'id_name_1')
  635. self.assertEqual(fields[1].choice_label, 'Paul')
  636. self.assertHTMLEqual(
  637. fields[1].tag(),
  638. '<input type="radio" name="name" value="paul" id="id_name_1" required />'
  639. )
  640. self.assertHTMLEqual(
  641. str(fields[1]),
  642. '<label for="id_name_1"><input type="radio" name="name" '
  643. 'value="paul" id="id_name_1" required /> Paul</label>'
  644. )
  645. def test_iterable_boundfield_select(self):
  646. class BeatleForm(Form):
  647. name = ChoiceField(choices=[('john', 'John'), ('paul', 'Paul'), ('george', 'George'), ('ringo', 'Ringo')])
  648. fields = list(BeatleForm(auto_id=False)['name'])
  649. self.assertEqual(len(fields), 4)
  650. self.assertEqual(fields[0].id_for_label, 'id_name_0')
  651. self.assertEqual(fields[0].choice_label, 'John')
  652. self.assertHTMLEqual(fields[0].tag(), '<option value="john">John</option>')
  653. self.assertHTMLEqual(str(fields[0]), '<option value="john">John</option>')
  654. def test_form_with_noniterable_boundfield(self):
  655. # You can iterate over any BoundField, not just those with widget=RadioSelect.
  656. class BeatleForm(Form):
  657. name = CharField()
  658. f = BeatleForm(auto_id=False)
  659. self.assertHTMLEqual('\n'.join(str(bf) for bf in f['name']), '<input type="text" name="name" required />')
  660. def test_boundfield_slice(self):
  661. class BeatleForm(Form):
  662. name = ChoiceField(
  663. choices=[('john', 'John'), ('paul', 'Paul'), ('george', 'George'), ('ringo', 'Ringo')],
  664. widget=RadioSelect,
  665. )
  666. f = BeatleForm()
  667. bf = f['name']
  668. self.assertEqual(
  669. [str(item) for item in bf[1:]],
  670. [str(bf[1]), str(bf[2]), str(bf[3])],
  671. )
  672. def test_forms_with_multiple_choice(self):
  673. # MultipleChoiceField is a special case, as its data is required to be a list:
  674. class SongForm(Form):
  675. name = CharField()
  676. composers = MultipleChoiceField()
  677. f = SongForm(auto_id=False)
  678. self.assertHTMLEqual(str(f['composers']), """<select multiple="multiple" name="composers" required>
  679. </select>""")
  680. class SongForm(Form):
  681. name = CharField()
  682. composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')])
  683. f = SongForm(auto_id=False)
  684. self.assertHTMLEqual(str(f['composers']), """<select multiple="multiple" name="composers" required>
  685. <option value="J">John Lennon</option>
  686. <option value="P">Paul McCartney</option>
  687. </select>""")
  688. f = SongForm({'name': 'Yesterday', 'composers': ['P']}, auto_id=False)
  689. self.assertHTMLEqual(str(f['name']), '<input type="text" name="name" value="Yesterday" required />')
  690. self.assertHTMLEqual(str(f['composers']), """<select multiple="multiple" name="composers" required>
  691. <option value="J">John Lennon</option>
  692. <option value="P" selected>Paul McCartney</option>
  693. </select>""")
  694. def test_form_with_disabled_fields(self):
  695. class PersonForm(Form):
  696. name = CharField()
  697. birthday = DateField(disabled=True)
  698. class PersonFormFieldInitial(Form):
  699. name = CharField()
  700. birthday = DateField(disabled=True, initial=datetime.date(1974, 8, 16))
  701. # Disabled fields are generally not transmitted by user agents.
  702. # The value from the form's initial data is used.
  703. f1 = PersonForm({'name': 'John Doe'}, initial={'birthday': datetime.date(1974, 8, 16)})
  704. f2 = PersonFormFieldInitial({'name': 'John Doe'})
  705. for form in (f1, f2):
  706. self.assertTrue(form.is_valid())
  707. self.assertEqual(
  708. form.cleaned_data,
  709. {'birthday': datetime.date(1974, 8, 16), 'name': 'John Doe'}
  710. )
  711. # Values provided in the form's data are ignored.
  712. data = {'name': 'John Doe', 'birthday': '1984-11-10'}
  713. f1 = PersonForm(data, initial={'birthday': datetime.date(1974, 8, 16)})
  714. f2 = PersonFormFieldInitial(data)
  715. for form in (f1, f2):
  716. self.assertTrue(form.is_valid())
  717. self.assertEqual(
  718. form.cleaned_data,
  719. {'birthday': datetime.date(1974, 8, 16), 'name': 'John Doe'}
  720. )
  721. # Initial data remains present on invalid forms.
  722. data = {}
  723. f1 = PersonForm(data, initial={'birthday': datetime.date(1974, 8, 16)})
  724. f2 = PersonFormFieldInitial(data)
  725. for form in (f1, f2):
  726. self.assertFalse(form.is_valid())
  727. self.assertEqual(form['birthday'].value(), datetime.date(1974, 8, 16))
  728. def test_hidden_data(self):
  729. class SongForm(Form):
  730. name = CharField()
  731. composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')])
  732. # MultipleChoiceField rendered as_hidden() is a special case. Because it can
  733. # have multiple values, its as_hidden() renders multiple <input type="hidden">
  734. # tags.
  735. f = SongForm({'name': 'Yesterday', 'composers': ['P']}, auto_id=False)
  736. self.assertHTMLEqual(f['composers'].as_hidden(), '<input type="hidden" name="composers" value="P" />')
  737. f = SongForm({'name': 'From Me To You', 'composers': ['P', 'J']}, auto_id=False)
  738. self.assertHTMLEqual(f['composers'].as_hidden(), """<input type="hidden" name="composers" value="P" />
  739. <input type="hidden" name="composers" value="J" />""")
  740. # DateTimeField rendered as_hidden() is special too
  741. class MessageForm(Form):
  742. when = SplitDateTimeField()
  743. f = MessageForm({'when_0': '1992-01-01', 'when_1': '01:01'})
  744. self.assertTrue(f.is_valid())
  745. self.assertHTMLEqual(
  746. str(f['when']),
  747. '<input type="text" name="when_0" value="1992-01-01" id="id_when_0" required />'
  748. '<input type="text" name="when_1" value="01:01" id="id_when_1" required />'
  749. )
  750. self.assertHTMLEqual(
  751. f['when'].as_hidden(),
  752. '<input type="hidden" name="when_0" value="1992-01-01" id="id_when_0" />'
  753. '<input type="hidden" name="when_1" value="01:01" id="id_when_1" />'
  754. )
  755. def test_multiple_choice_checkbox(self):
  756. # MultipleChoiceField can also be used with the CheckboxSelectMultiple widget.
  757. class SongForm(Form):
  758. name = CharField()
  759. composers = MultipleChoiceField(
  760. choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')],
  761. widget=CheckboxSelectMultiple,
  762. )
  763. f = SongForm(auto_id=False)
  764. self.assertHTMLEqual(str(f['composers']), """<ul>
  765. <li><label><input type="checkbox" name="composers" value="J" /> John Lennon</label></li>
  766. <li><label><input type="checkbox" name="composers" value="P" /> Paul McCartney</label></li>
  767. </ul>""")
  768. f = SongForm({'composers': ['J']}, auto_id=False)
  769. self.assertHTMLEqual(str(f['composers']), """<ul>
  770. <li><label><input checked type="checkbox" name="composers" value="J" /> John Lennon</label></li>
  771. <li><label><input type="checkbox" name="composers" value="P" /> Paul McCartney</label></li>
  772. </ul>""")
  773. f = SongForm({'composers': ['J', 'P']}, auto_id=False)
  774. self.assertHTMLEqual(str(f['composers']), """<ul>
  775. <li><label><input checked type="checkbox" name="composers" value="J" /> John Lennon</label></li>
  776. <li><label><input checked type="checkbox" name="composers" value="P" /> Paul McCartney</label></li>
  777. </ul>""")
  778. # Test iterating on individual checkboxes in a template
  779. t = Template('{% for checkbox in form.composers %}<div class="mycheckbox">{{ checkbox }}</div>{% endfor %}')
  780. self.assertHTMLEqual(t.render(Context({'form': f})), """<div class="mycheckbox"><label>
  781. <input checked name="composers" type="checkbox" value="J" /> John Lennon</label></div>
  782. <div class="mycheckbox"><label>
  783. <input checked name="composers" type="checkbox" value="P" /> Paul McCartney</label></div>""")
  784. def test_checkbox_auto_id(self):
  785. # Regarding auto_id, CheckboxSelectMultiple is a special case. Each checkbox
  786. # gets a distinct ID, formed by appending an underscore plus the checkbox's
  787. # zero-based index.
  788. class SongForm(Form):
  789. name = CharField()
  790. composers = MultipleChoiceField(
  791. choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')],
  792. widget=CheckboxSelectMultiple,
  793. )
  794. f = SongForm(auto_id='%s_id')
  795. self.assertHTMLEqual(
  796. str(f['composers']),
  797. """<ul id="composers_id">
  798. <li><label for="composers_id_0">
  799. <input type="checkbox" name="composers" value="J" id="composers_id_0" /> John Lennon</label></li>
  800. <li><label for="composers_id_1">
  801. <input type="checkbox" name="composers" value="P" id="composers_id_1" /> Paul McCartney</label></li>
  802. </ul>"""
  803. )
  804. def test_multiple_choice_list_data(self):
  805. # Data for a MultipleChoiceField should be a list. QueryDict and
  806. # MultiValueDict conveniently work with this.
  807. class SongForm(Form):
  808. name = CharField()
  809. composers = MultipleChoiceField(
  810. choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')],
  811. widget=CheckboxSelectMultiple,
  812. )
  813. data = {'name': 'Yesterday', 'composers': ['J', 'P']}
  814. f = SongForm(data)
  815. self.assertEqual(f.errors, {})
  816. data = QueryDict('name=Yesterday&composers=J&composers=P')
  817. f = SongForm(data)
  818. self.assertEqual(f.errors, {})
  819. data = MultiValueDict(dict(name=['Yesterday'], composers=['J', 'P']))
  820. f = SongForm(data)
  821. self.assertEqual(f.errors, {})
  822. # SelectMultiple uses ducktyping so that MultiValueDictLike.getlist()
  823. # is called.
  824. f = SongForm(MultiValueDictLike({'name': 'Yesterday', 'composers': 'J'}))
  825. self.assertEqual(f.errors, {})
  826. self.assertEqual(f.cleaned_data['composers'], ['J'])
  827. def test_multiple_hidden(self):
  828. class SongForm(Form):
  829. name = CharField()
  830. composers = MultipleChoiceField(
  831. choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')],
  832. widget=CheckboxSelectMultiple,
  833. )
  834. # The MultipleHiddenInput widget renders multiple values as hidden fields.
  835. class SongFormHidden(Form):
  836. name = CharField()
  837. composers = MultipleChoiceField(
  838. choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')],
  839. widget=MultipleHiddenInput,
  840. )
  841. f = SongFormHidden(MultiValueDict(dict(name=['Yesterday'], composers=['J', 'P'])), auto_id=False)
  842. self.assertHTMLEqual(
  843. f.as_ul(),
  844. """<li>Name: <input type="text" name="name" value="Yesterday" required />
  845. <input type="hidden" name="composers" value="J" />
  846. <input type="hidden" name="composers" value="P" /></li>"""
  847. )
  848. # When using CheckboxSelectMultiple, the framework expects a list of input and
  849. # returns a list of input.
  850. f = SongForm({'name': 'Yesterday'}, auto_id=False)
  851. self.assertEqual(f.errors['composers'], ['This field is required.'])
  852. f = SongForm({'name': 'Yesterday', 'composers': ['J']}, auto_id=False)
  853. self.assertEqual(f.errors, {})
  854. self.assertEqual(f.cleaned_data['composers'], ['J'])
  855. self.assertEqual(f.cleaned_data['name'], 'Yesterday')
  856. f = SongForm({'name': 'Yesterday', 'composers': ['J', 'P']}, auto_id=False)
  857. self.assertEqual(f.errors, {})
  858. self.assertEqual(f.cleaned_data['composers'], ['J', 'P'])
  859. self.assertEqual(f.cleaned_data['name'], 'Yesterday')
  860. # MultipleHiddenInput uses ducktyping so that
  861. # MultiValueDictLike.getlist() is called.
  862. f = SongForm(MultiValueDictLike({'name': 'Yesterday', 'composers': 'J'}))
  863. self.assertEqual(f.errors, {})
  864. self.assertEqual(f.cleaned_data['composers'], ['J'])
  865. def test_escaping(self):
  866. # Validation errors are HTML-escaped when output as HTML.
  867. class EscapingForm(Form):
  868. special_name = CharField(label="<em>Special</em> Field")
  869. special_safe_name = CharField(label=mark_safe("<em>Special</em> Field"))
  870. def clean_special_name(self):
  871. raise ValidationError("Something's wrong with '%s'" % self.cleaned_data['special_name'])
  872. def clean_special_safe_name(self):
  873. raise ValidationError(
  874. mark_safe("'<b>%s</b>' is a safe string" % self.cleaned_data['special_safe_name'])
  875. )
  876. f = EscapingForm({
  877. 'special_name':
  878. "Nothing to escape",
  879. 'special_safe_name': "Nothing to escape",
  880. }, auto_id=False)
  881. self.assertHTMLEqual(
  882. f.as_table(),
  883. """<tr><th>&lt;em&gt;Special&lt;/em&gt; Field:</th><td>
  884. <ul class="errorlist"><li>Something&#39;s wrong with &#39;Nothing to escape&#39;</li></ul>
  885. <input type="text" name="special_name" value="Nothing to escape" required /></td></tr>
  886. <tr><th><em>Special</em> Field:</th><td>
  887. <ul class="errorlist"><li>'<b>Nothing to escape</b>' is a safe string</li></ul>
  888. <input type="text" name="special_safe_name" value="Nothing to escape" required /></td></tr>"""
  889. )
  890. f = EscapingForm({
  891. 'special_name': "Should escape < & > and <script>alert('xss')</script>",
  892. 'special_safe_name': "<i>Do not escape</i>"
  893. }, auto_id=False)
  894. self.assertHTMLEqual(
  895. f.as_table(),
  896. """<tr><th>&lt;em&gt;Special&lt;/em&gt; Field:</th><td>
  897. <ul class="errorlist"><li>Something&#39;s wrong with &#39;Should escape &lt; &amp; &gt; and
  898. &lt;script&gt;alert(&#39;xss&#39;)&lt;/script&gt;&#39;</li></ul>
  899. <input type="text" name="special_name"
  900. value="Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#39;xss&#39;)&lt;/script&gt;" required /></td></tr>
  901. <tr><th><em>Special</em> Field:</th><td>
  902. <ul class="errorlist"><li>'<b><i>Do not escape</i></b>' is a safe string</li></ul>
  903. <input type="text" name="special_safe_name" value="&lt;i&gt;Do not escape&lt;/i&gt;" required /></td></tr>"""
  904. )
  905. def test_validating_multiple_fields(self):
  906. # There are a couple of ways to do multiple-field validation. If you want the
  907. # validation message to be associated with a particular field, implement the
  908. # clean_XXX() method on the Form, where XXX is the field name. As in
  909. # Field.clean(), the clean_XXX() method should return the cleaned value. In the
  910. # clean_XXX() method, you have access to self.cleaned_data, which is a dictionary
  911. # of all the data that has been cleaned *so far*, in order by the fields,
  912. # including the current field (e.g., the field XXX if you're in clean_XXX()).
  913. class UserRegistration(Form):
  914. username = CharField(max_length=10)
  915. password1 = CharField(widget=PasswordInput)
  916. password2 = CharField(widget=PasswordInput)
  917. def clean_password2(self):
  918. if (self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and
  919. self.cleaned_data['password1'] != self.cleaned_data['password2']):
  920. raise ValidationError('Please make sure your passwords match.')
  921. return self.cleaned_data['password2']
  922. f = UserRegistration(auto_id=False)
  923. self.assertEqual(f.errors, {})
  924. f = UserRegistration({}, auto_id=False)
  925. self.assertEqual(f.errors['username'], ['This field is required.'])
  926. self.assertEqual(f.errors['password1'], ['This field is required.'])
  927. self.assertEqual(f.errors['password2'], ['This field is required.'])
  928. f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)
  929. self.assertEqual(f.errors['password2'], ['Please make sure your passwords match.'])
  930. f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'foo'}, auto_id=False)
  931. self.assertEqual(f.errors, {})
  932. self.assertEqual(f.cleaned_data['username'], 'adrian')
  933. self.assertEqual(f.cleaned_data['password1'], 'foo')
  934. self.assertEqual(f.cleaned_data['password2'], 'foo')
  935. # Another way of doing multiple-field validation is by implementing the
  936. # Form's clean() method. Usually ValidationError raised by that method
  937. # will not be associated with a particular field and will have a
  938. # special-case association with the field named '__all__'. It's
  939. # possible to associate the errors to particular field with the
  940. # Form.add_error() method or by passing a dictionary that maps each
  941. # field to one or more errors.
  942. #
  943. # Note that in Form.clean(), you have access to self.cleaned_data, a
  944. # dictionary of all the fields/values that have *not* raised a
  945. # ValidationError. Also note Form.clean() is required to return a
  946. # dictionary of all clean data.
  947. class UserRegistration(Form):
  948. username = CharField(max_length=10)
  949. password1 = CharField(widget=PasswordInput)
  950. password2 = CharField(widget=PasswordInput)
  951. def clean(self):
  952. # Test raising a ValidationError as NON_FIELD_ERRORS.
  953. if (self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and
  954. self.cleaned_data['password1'] != self.cleaned_data['password2']):
  955. raise ValidationError('Please make sure your passwords match.')
  956. # Test raising ValidationError that targets multiple fields.
  957. errors = {}
  958. if self.cleaned_data.get('password1') == 'FORBIDDEN_VALUE':
  959. errors['password1'] = 'Forbidden value.'
  960. if self.cleaned_data.get('password2') == 'FORBIDDEN_VALUE':
  961. errors['password2'] = ['Forbidden value.']
  962. if errors:
  963. raise ValidationError(errors)
  964. # Test Form.add_error()
  965. if self.cleaned_data.get('password1') == 'FORBIDDEN_VALUE2':
  966. self.add_error(None, 'Non-field error 1.')
  967. self.add_error('password1', 'Forbidden value 2.')
  968. if self.cleaned_data.get('password2') == 'FORBIDDEN_VALUE2':
  969. self.add_error('password2', 'Forbidden value 2.')
  970. raise ValidationError('Non-field error 2.')
  971. return self.cleaned_data
  972. f = UserRegistration(auto_id=False)
  973. self.assertEqual(f.errors, {})
  974. f = UserRegistration({}, auto_id=False)
  975. self.assertHTMLEqual(
  976. f.as_table(),
  977. """<tr><th>Username:</th><td>
  978. <ul class="errorlist"><li>This field is required.</li></ul>
  979. <input type="text" name="username" maxlength="10" required /></td></tr>
  980. <tr><th>Password1:</th><td><ul class="errorlist"><li>This field is required.</li></ul>
  981. <input type="password" name="password1" required /></td></tr>
  982. <tr><th>Password2:</th><td><ul class="errorlist"><li>This field is required.</li></ul>
  983. <input type="password" name="password2" required /></td></tr>"""
  984. )
  985. self.assertEqual(f.errors['username'], ['This field is required.'])
  986. self.assertEqual(f.errors['password1'], ['This field is required.'])
  987. self.assertEqual(f.errors['password2'], ['This field is required.'])
  988. f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)
  989. self.assertEqual(f.errors['__all__'], ['Please make sure your passwords match.'])
  990. self.assertHTMLEqual(
  991. f.as_table(),
  992. """<tr><td colspan="2">
  993. <ul class="errorlist nonfield"><li>Please make sure your passwords match.</li></ul></td></tr>
  994. <tr><th>Username:</th><td><input type="text" name="username" value="adrian" maxlength="10" required /></td></tr>
  995. <tr><th>Password1:</th><td><input type="password" name="password1" required /></td></tr>
  996. <tr><th>Password2:</th><td><input type="password" name="password2" required /></td></tr>"""
  997. )
  998. self.assertHTMLEqual(
  999. f.as_ul(),
  1000. """<li><ul class="errorlist nonfield">
  1001. <li>Please make sure your passwords match.</li></ul></li>
  1002. <li>Username: <input type="text" name="username" value="adrian" maxlength="10" required /></li>
  1003. <li>Password1: <input type="password" name="password1" required /></li>
  1004. <li>Password2: <input type="password" name="password2" required /></li>"""
  1005. )
  1006. f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'foo'}, auto_id=False)
  1007. self.assertEqual(f.errors, {})
  1008. self.assertEqual(f.cleaned_data['username'], 'adrian')
  1009. self.assertEqual(f.cleaned_data['password1'], 'foo')
  1010. self.assertEqual(f.cleaned_data['password2'], 'foo')
  1011. f = UserRegistration({
  1012. 'username': 'adrian',
  1013. 'password1': 'FORBIDDEN_VALUE',
  1014. 'password2': 'FORBIDDEN_VALUE',
  1015. }, auto_id=False)
  1016. self.assertEqual(f.errors['password1'], ['Forbidden value.'])
  1017. self.assertEqual(f.errors['password2'], ['Forbidden value.'])
  1018. f = UserRegistration({
  1019. 'username': 'adrian',
  1020. 'password1': 'FORBIDDEN_VALUE2',
  1021. 'password2': 'FORBIDDEN_VALUE2',
  1022. }, auto_id=False)
  1023. self.assertEqual(f.errors['__all__'], ['Non-field error 1.', 'Non-field error 2.'])
  1024. self.assertEqual(f.errors['password1'], ['Forbidden value 2.'])
  1025. self.assertEqual(f.errors['password2'], ['Forbidden value 2.'])
  1026. with self.assertRaisesMessage(ValueError, "has no field named"):
  1027. f.add_error('missing_field', 'Some error.')
  1028. def test_update_error_dict(self):
  1029. class CodeForm(Form):
  1030. code = CharField(max_length=10)
  1031. def clean(self):
  1032. try:
  1033. raise ValidationError({'code': [ValidationError('Code error 1.')]})
  1034. except ValidationError as e:
  1035. self._errors = e.update_error_dict(self._errors)
  1036. try:
  1037. raise ValidationError({'code': [ValidationError('Code error 2.')]})
  1038. except ValidationError as e:
  1039. self._errors = e.update_error_dict(self._errors)
  1040. try:
  1041. raise ValidationError({'code': forms.ErrorList(['Code error 3.'])})
  1042. except ValidationError as e:
  1043. self._errors = e.update_error_dict(self._errors)
  1044. try:
  1045. raise ValidationError('Non-field error 1.')
  1046. except ValidationError as e:
  1047. self._errors = e.update_error_dict(self._errors)
  1048. try:
  1049. raise ValidationError([ValidationError('Non-field error 2.')])
  1050. except ValidationError as e:
  1051. self._errors = e.update_error_dict(self._errors)
  1052. # The newly added list of errors is an instance of ErrorList.
  1053. for field, error_list in self._errors.items():
  1054. if not isinstance(error_list, self.error_class):
  1055. self._errors[field] = self.error_class(error_list)
  1056. form = CodeForm({'code': 'hello'})
  1057. # Trigger validation.
  1058. self.assertFalse(form.is_valid())
  1059. # update_error_dict didn't lose track of the ErrorDict type.
  1060. self.assertIsInstance(form._errors, forms.ErrorDict)
  1061. self.assertEqual(dict(form.errors), {
  1062. 'code': ['Code error 1.', 'Code error 2.', 'Code error 3.'],
  1063. NON_FIELD_ERRORS: ['Non-field error 1.', 'Non-field error 2.'],
  1064. })
  1065. def test_has_error(self):
  1066. class UserRegistration(Form):
  1067. username = CharField(max_length=10)
  1068. password1 = CharField(widget=PasswordInput, min_length=5)
  1069. password2 = CharField(widget=PasswordInput)
  1070. def clean(self):
  1071. if (self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and
  1072. self.cleaned_data['password1'] != self.cleaned_data['password2']):
  1073. raise ValidationError(
  1074. 'Please make sure your passwords match.',
  1075. code='password_mismatch',
  1076. )
  1077. f = UserRegistration(data={})
  1078. self.assertTrue(f.has_error('password1'))
  1079. self.assertTrue(f.has_error('password1', 'required'))
  1080. self.assertFalse(f.has_error('password1', 'anything'))
  1081. f = UserRegistration(data={'password1': 'Hi', 'password2': 'Hi'})
  1082. self.assertTrue(f.has_error('password1'))
  1083. self.assertTrue(f.has_error('password1', 'min_length'))
  1084. self.assertFalse(f.has_error('password1', 'anything'))
  1085. self.assertFalse(f.has_error('password2'))
  1086. self.assertFalse(f.has_error('password2', 'anything'))
  1087. f = UserRegistration(data={'password1': 'Bonjour', 'password2': 'Hello'})
  1088. self.assertFalse(f.has_error('password1'))
  1089. self.assertFalse(f.has_error('password1', 'required'))
  1090. self.assertTrue(f.has_error(NON_FIELD_ERRORS))
  1091. self.assertTrue(f.has_error(NON_FIELD_ERRORS, 'password_mismatch'))
  1092. self.assertFalse(f.has_error(NON_FIELD_ERRORS, 'anything'))
  1093. def test_dynamic_construction(self):
  1094. # It's possible to construct a Form dynamically by adding to the self.fields
  1095. # dictionary in __init__(). Don't forget to call Form.__init__() within the
  1096. # subclass' __init__().
  1097. class Person(Form):
  1098. first_name = CharField()
  1099. last_name = CharField()
  1100. def __init__(self, *args, **kwargs):
  1101. super(Person, self).__init__(*args, **kwargs)
  1102. self.fields['birthday'] = DateField()
  1103. p = Person(auto_id=False)
  1104. self.assertHTMLEqual(
  1105. p.as_table(),
  1106. """<tr><th>First name:</th><td><input type="text" name="first_name" required /></td></tr>
  1107. <tr><th>Last name:</th><td><input type="text" name="last_name" required /></td></tr>
  1108. <tr><th>Birthday:</th><td><input type="text" name="birthday" required /></td></tr>"""
  1109. )
  1110. # Instances of a dynamic Form do not persist fields from one Form instance to
  1111. # the next.
  1112. class MyForm(Form):
  1113. def __init__(self, data=None, auto_id=False, field_list=[]):
  1114. Form.__init__(self, data, auto_id=auto_id)
  1115. for field in field_list:
  1116. self.fields[field[0]] = field[1]
  1117. field_list = [('field1', CharField()), ('field2', CharField())]
  1118. my_form = MyForm(field_list=field_list)
  1119. self.assertHTMLEqual(
  1120. my_form.as_table(),
  1121. """<tr><th>Field1:</th><td><input type="text" name="field1" required /></td></tr>
  1122. <tr><th>Field2:</th><td><input type="text" name="field2" required /></td></tr>"""
  1123. )
  1124. field_list = [('field3', CharField()), ('field4', CharField())]
  1125. my_form = MyForm(field_list=field_list)
  1126. self.assertHTMLEqual(
  1127. my_form.as_table(),
  1128. """<tr><th>Field3:</th><td><input type="text" name="field3" required /></td></tr>
  1129. <tr><th>Field4:</th><td><input type="text" name="field4" required /></td></tr>"""
  1130. )
  1131. class MyForm(Form):
  1132. default_field_1 = CharField()
  1133. default_field_2 = CharField()
  1134. def __init__(self, data=None, auto_id=False, field_list=[]):
  1135. Form.__init__(self, data, auto_id=auto_id)
  1136. for field in field_list:
  1137. self.fields[field[0]] = field[1]
  1138. field_list = [('field1', CharField()), ('field2', CharField())]
  1139. my_form = MyForm(field_list=field_list)
  1140. self.assertHTMLEqual(
  1141. my_form.as_table(),
  1142. """<tr><th>Default field 1:</th><td><input type="text" name="default_field_1" required /></td></tr>
  1143. <tr><th>Default field 2:</th><td><input type="text" name="default_field_2" required /></td></tr>
  1144. <tr><th>Field1:</th><td><input type="text" name="field1" required /></td></tr>
  1145. <tr><th>Field2:</th><td><input type="text" name="field2" required /></td></tr>"""
  1146. )
  1147. field_list = [('field3', CharField()), ('field4', CharField())]
  1148. my_form = MyForm(field_list=field_list)
  1149. self.assertHTMLEqual(
  1150. my_form.as_table(),
  1151. """<tr><th>Default field 1:</th><td><input type="text" name="default_field_1" required /></td></tr>
  1152. <tr><th>Default field 2:</th><td><input type="text" name="default_field_2" required /></td></tr>
  1153. <tr><th>Field3:</th><td><input type="text" name="field3" required /></td></tr>
  1154. <tr><th>Field4:</th><td><input type="text" name="field4" required /></td></tr>"""
  1155. )
  1156. # Similarly, changes to field attributes do not persist from one Form instance
  1157. # to the next.
  1158. class Person(Form):
  1159. first_name = CharField(required=False)
  1160. last_name = CharField(required=False)
  1161. def __init__(self, names_required=False, *args, **kwargs):
  1162. super(Person, self).__init__(*args, **kwargs)
  1163. if names_required:
  1164. self.fields['first_name'].required = True
  1165. self.fields['first_name'].widget.attrs['class'] = 'required'
  1166. self.fields['last_name'].required = True
  1167. self.fields['last_name'].widget.attrs['class'] = 'required'
  1168. f = Person(names_required=False)
  1169. self.assertEqual(f['first_name'].field.required, f['last_name'].field.required, (False, False))
  1170. self.assertEqual(f['first_name'].field.widget.attrs, f['last_name'].field.widget.attrs, ({}, {}))
  1171. f = Person(names_required=True)
  1172. self.assertEqual(f['first_name'].field.required, f['last_name'].field.required, (True, True))
  1173. self.assertEqual(
  1174. f['first_name'].field.widget.attrs,
  1175. f['last_name'].field.widget.attrs,
  1176. ({'class': 'reuired'}, {'class': 'required'})
  1177. )
  1178. f = Person(names_required=False)
  1179. self.assertEqual(f['first_name'].field.required, f['last_name'].field.required, (False, False))
  1180. self.assertEqual(f['first_name'].field.widget.attrs, f['last_name'].field.widget.attrs, ({}, {}))
  1181. class Person(Form):
  1182. first_name = CharField(max_length=30)
  1183. last_name = CharField(max_length=30)
  1184. def __init__(self, name_max_length=None, *args, **kwargs):
  1185. super(Person, self).__init__(*args, **kwargs)
  1186. if name_max_length:
  1187. self.fields['first_name'].max_length = name_max_length
  1188. self.fields['last_name'].max_length = name_max_length
  1189. f = Person(name_max_length=None)
  1190. self.assertEqual(f['first_name'].field.max_length, f['last_name'].field.max_length, (30, 30))
  1191. f = Person(name_max_length=20)
  1192. self.assertEqual(f['first_name'].field.max_length, f['last_name'].field.max_length, (20, 20))
  1193. f = Person(name_max_length=None)
  1194. self.assertEqual(f['first_name'].field.max_length, f['last_name'].field.max_length, (30, 30))
  1195. # Similarly, choices do not persist from one Form instance to the next.
  1196. # Refs #15127.
  1197. class Person(Form):
  1198. first_name = CharField(required=False)
  1199. last_name = CharField(required=False)
  1200. gender = ChoiceField(choices=(('f', 'Female'), ('m', 'Male')))
  1201. def __init__(self, allow_unspec_gender=False, *args, **kwargs):
  1202. super(Person, self).__init__(*args, **kwargs)
  1203. if allow_unspec_gender:
  1204. self.fields['gender'].choices += (('u', 'Unspecified'),)
  1205. f = Person()
  1206. self.assertEqual(f['gender'].field.choices, [('f', 'Female'), ('m', 'Male')])
  1207. f = Person(allow_unspec_gender=True)
  1208. self.assertEqual(f['gender'].field.choices, [('f', 'Female'), ('m', 'Male'), ('u', 'Unspecified')])
  1209. f = Person()
  1210. self.assertEqual(f['gender'].field.choices, [('f', 'Female'), ('m', 'Male')])
  1211. def test_validators_independence(self):
  1212. """
  1213. The list of form field validators can be modified without polluting
  1214. other forms.
  1215. """
  1216. class MyForm(Form):
  1217. myfield = CharField(max_length=25)
  1218. f1 = MyForm()
  1219. f2 = MyForm()
  1220. f1.fields['myfield'].validators[0] = MaxValueValidator(12)
  1221. self.assertNotEqual(f1.fields['myfield'].validators[0], f2.fields['myfield'].validators[0])
  1222. def test_hidden_widget(self):
  1223. # HiddenInput widgets are displayed differently in the as_table(), as_ul())
  1224. # and as_p() output of a Form -- their verbose names are not displayed, and a
  1225. # separate row is not displayed. They're displayed in the last row of the
  1226. # form, directly after that row's form element.
  1227. class Person(Form):
  1228. first_name = CharField()
  1229. last_name = CharField()
  1230. hidden_text = CharField(widget=HiddenInput)
  1231. birthday = DateField()
  1232. p = Person(auto_id=False)
  1233. self.assertHTMLEqual(
  1234. p.as_table(),
  1235. """<tr><th>First name:</th><td><input type="text" name="first_name" required /></td></tr>
  1236. <tr><th>Last name:</th><td><input type="text" name="last_name" required /></td></tr>
  1237. <tr><th>Birthday:</th>
  1238. <td><input type="text" name="birthday" required /><input type="hidden" name="hidden_text" /></td></tr>"""
  1239. )
  1240. self.assertHTMLEqual(
  1241. p.as_ul(),
  1242. """<li>First name: <input type="text" name="first_name" required /></li>
  1243. <li>Last name: <input type="text" name="last_name" required /></li>
  1244. <li>Birthday: <input type="text" name="birthday" required /><input type="hidden" name="hidden_text" /></li>"""
  1245. )
  1246. self.assertHTMLEqual(
  1247. p.as_p(), """<p>First name: <input type="text" name="first_name" required /></p>
  1248. <p>Last name: <input type="text" name="last_name" required /></p>
  1249. <p>Birthday: <input type="text" name="birthday" required /><input type="hidden" name="hidden_text" /></p>"""
  1250. )
  1251. # With auto_id set, a HiddenInput still gets an ID, but it doesn't get a label.
  1252. p = Person(auto_id='id_%s')
  1253. self.assertHTMLEqual(
  1254. p.as_table(),
  1255. """<tr><th><label for="id_first_name">First name:</label></th><td>
  1256. <input type="text" name="first_name" id="id_first_name" required /></td></tr>
  1257. <tr><th><label for="id_last_name">Last name:</label></th><td>
  1258. <input type="text" name="last_name" id="id_last_name" required /></td></tr>
  1259. <tr><th><label for="id_birthday">Birthday:</label></th><td>
  1260. <input type="text" name="birthday" id="id_birthday" required />
  1261. <input type="hidden" name="hidden_text" id="id_hidden_text" /></td></tr>"""
  1262. )
  1263. self.assertHTMLEqual(
  1264. p.as_ul(),
  1265. """<li><label for="id_first_name">First name:</label>
  1266. <input type="text" name="first_name" id="id_first_name" required /></li>
  1267. <li><label for="id_last_name">Last name:</label>
  1268. <input type="text" name="last_name" id="id_last_name" required /></li>
  1269. <li><label for="id_birthday">Birthday:</label>
  1270. <input type="text" name="birthday" id="id_birthday" required />
  1271. <input type="hidden" name="hidden_text" id="id_hidden_text" /></li>"""
  1272. )
  1273. self.assertHTMLEqual(
  1274. p.as_p(),
  1275. """<p><label for="id_first_name">First name:</label>
  1276. <input type="text" name="first_name" id="id_first_name" required /></p>
  1277. <p><label for="id_last_name">Last name:</label>
  1278. <input type="text" name="last_name" id="id_last_name" required /></p>
  1279. <p><label for="id_birthday">Birthday:</label>
  1280. <input type="text" name="birthday" id="id_birthday" required />
  1281. <input type="hidden" name="hidden_text" id="id_hidden_text" /></p>"""
  1282. )
  1283. # If a field with a HiddenInput has errors, the as_table() and as_ul() output
  1284. # will include the error message(s) with the text "(Hidden field [fieldname]) "
  1285. # prepended. This message is displayed at the top of the output, regardless of
  1286. # its field's order in the form.
  1287. p = Person({'first_name': 'John', 'last_name': 'Lennon', 'birthday': '1940-10-9'}, auto_id=False)
  1288. self.assertHTMLEqual(
  1289. p.as_table(),
  1290. """<tr><td colspan="2">
  1291. <ul class="errorlist nonfield"><li>(Hidden field hidden_text) This field is required.</li></ul></td></tr>
  1292. <tr><th>First name:</th><td><input type="text" name="first_name" value="John" required /></td></tr>
  1293. <tr><th>Last name:</th><td><input type="text" name="last_name" value="Lennon" required /></td></tr>
  1294. <tr><th>Birthday:</th><td><input type="text" name="birthday" value="1940-10-9" required />
  1295. <input type="hidden" name="hidden_text" /></td></tr>"""
  1296. )
  1297. self.assertHTMLEqual(
  1298. p.as_ul(),
  1299. """<li><ul class="errorlist nonfield"><li>(Hidden field hidden_text) This field is required.</li></ul></li>
  1300. <li>First name: <input type="text" name="first_name" value="John" required /></li>
  1301. <li>Last name: <input type="text" name="last_name" value="Lennon" required /></li>
  1302. <li>Birthday: <input type="text" name="birthday" value="1940-10-9" required />
  1303. <input type="hidden" name="hidden_text" /></li>"""
  1304. )
  1305. self.assertHTMLEqual(
  1306. p.as_p(),
  1307. """<ul class="errorlist nonfield"><li>(Hidden field hidden_text) This field is required.</li></ul>
  1308. <p>First name: <input type="text" name="first_name" value="John" required /></p>
  1309. <p>Last name: <input type="text" name="last_name" value="Lennon" required /></p>
  1310. <p>Birthday: <input type="text" name="birthday" value="1940-10-9" required />
  1311. <input type="hidden" name="hidden_text" /></p>"""
  1312. )
  1313. # A corner case: It's possible for a form to have only HiddenInputs.
  1314. class TestForm(Form):
  1315. foo = CharField(widget=HiddenInput)
  1316. bar = CharField(widget=HiddenInput)
  1317. p = TestForm(auto_id=False)
  1318. self.assertHTMLEqual(p.as_table(), '<input type="hidden" name="foo" /><input type="hidden" name="bar" />')
  1319. self.assertHTMLEqual(p.as_ul(), '<input type="hidden" name="foo" /><input type="hidden" name="bar" />')
  1320. self.assertHTMLEqual(p.as_p(), '<input type="hidden" name="foo" /><input type="hidden" name="bar" />')
  1321. def test_field_order(self):
  1322. # A Form's fields are displayed in the same order in which they were defined.
  1323. class TestForm(Form):
  1324. field1 = CharField()
  1325. field2 = CharField()
  1326. field3 = CharField()
  1327. field4 = CharField()
  1328. field5 = CharField()
  1329. field6 = CharField()
  1330. field7 = CharField()
  1331. field8 = CharField()
  1332. field9 = CharField()
  1333. field10 = CharField()
  1334. field11 = CharField()
  1335. field12 = CharField()
  1336. field13 = CharField()
  1337. field14 = CharField()
  1338. p = TestForm(auto_id=False)
  1339. self.assertHTMLEqual(p.as_table(), """<tr><th>Field1:</th><td><input type="text" name="field1" required /></td></tr>
  1340. <tr><th>Field2:</th><td><input type="text" name="field2" required /></td></tr>
  1341. <tr><th>Field3:</th><td><input type="text" name="field3" required /></td></tr>
  1342. <tr><th>Field4:</th><td><input type="text" name="field4" required /></td></tr>
  1343. <tr><th>Field5:</th><td><input type="text" name="field5" required /></td></tr>
  1344. <tr><th>Field6:</th><td><input type="text" name="field6" required /></td></tr>
  1345. <tr><th>Field7:</th><td><input type="text" name="field7" required /></td></tr>
  1346. <tr><th>Field8:</th><td><input type="text" name="field8" required /></td></tr>
  1347. <tr><th>Field9:</th><td><input type="text" name="field9" required /></td></tr>
  1348. <tr><th>Field10:</th><td><input type="text" name="field10" required /></td></tr>
  1349. <tr><th>Field11:</th><td><input type="text" name="field11" required /></td></tr>
  1350. <tr><th>Field12:</th><td><input type="text" name="field12" required /></td></tr>
  1351. <tr><th>Field13:</th><td><input type="text" name="field13" required /></td></tr>
  1352. <tr><th>Field14:</th><td><input type="text" name="field14" required /></td></tr>""")
  1353. def test_explicit_field_order(self):
  1354. class TestFormParent(Form):
  1355. field1 = CharField()
  1356. field2 = CharField()
  1357. field4 = CharField()
  1358. field5 = CharField()
  1359. field6 = CharField()
  1360. field_order = ['field6', 'field5', 'field4', 'field2', 'field1']
  1361. class TestForm(TestFormParent):
  1362. field3 = CharField()
  1363. field_order = ['field2', 'field4', 'field3', 'field5', 'field6']
  1364. class TestFormRemove(TestForm):
  1365. field1 = None
  1366. class TestFormMissing(TestForm):
  1367. field_order = ['field2', 'field4', 'field3', 'field5', 'field6', 'field1']
  1368. field1 = None
  1369. class TestFormInit(TestFormParent):
  1370. field3 = CharField()
  1371. field_order = None
  1372. def __init__(self, **kwargs):
  1373. super(TestFormInit, self).__init__(**kwargs)
  1374. self.order_fields(field_order=TestForm.field_order)
  1375. p = TestFormParent()
  1376. self.assertEqual(list(p.fields.keys()), TestFormParent.field_order)
  1377. p = TestFormRemove()
  1378. self.assertEqual(list(p.fields.keys()), TestForm.field_order)
  1379. p = TestFormMissing()
  1380. self.assertEqual(list(p.fields.keys()), TestForm.field_order)
  1381. p = TestForm()
  1382. self.assertEqual(list(p.fields.keys()), TestFormMissing.field_order)
  1383. p = TestFormInit()
  1384. order = list(TestForm.field_order) + ['field1']
  1385. self.assertEqual(list(p.fields.keys()), order)
  1386. TestForm.field_order = ['unknown']
  1387. p = TestForm()
  1388. self.assertEqual(list(p.fields.keys()), ['field1', 'field2', 'field4', 'field5', 'field6', 'field3'])
  1389. def test_form_html_attributes(self):
  1390. # Some Field classes have an effect on the HTML attributes of their associated
  1391. # Widget. If you set max_length in a CharField and its associated widget is
  1392. # either a TextInput or PasswordInput, then the widget's rendered HTML will
  1393. # include the "maxlength" attribute.
  1394. class UserRegistration(Form):
  1395. username = CharField(max_length=10) # uses TextInput by default
  1396. password = CharField(max_length=10, widget=PasswordInput)
  1397. realname = CharField(max_length=10, widget=TextInput) # redundantly define widget, just to test
  1398. address = CharField() # no max_length defined here
  1399. p = UserRegistration(auto_id=False)
  1400. self.assertHTMLEqual(
  1401. p.as_ul(),
  1402. """<li>Username: <input type="text" name="username" maxlength="10" required /></li>
  1403. <li>Password: <input type="password" name="password" maxlength="10" required /></li>
  1404. <li>Realname: <input type="text" name="realname" maxlength="10" required /></li>
  1405. <li>Address: <input type="text" name="address" required /></li>"""
  1406. )
  1407. # If you specify a custom "attrs" that includes the "maxlength" attribute,
  1408. # the Field's max_length attribute will override whatever "maxlength" you specify
  1409. # in "attrs".
  1410. class UserRegistration(Form):
  1411. username = CharField(max_length=10, widget=TextInput(attrs={'maxlength': 20}))
  1412. password = CharField(max_length=10, widget=PasswordInput)
  1413. p = UserRegistration(auto_id=False)
  1414. self.assertHTMLEqual(
  1415. p.as_ul(),
  1416. """<li>Username: <input type="text" name="username" maxlength="10" required /></li>
  1417. <li>Password: <input type="password" name="password" maxlength="10" required /></li>"""
  1418. )
  1419. def test_specifying_labels(self):
  1420. # You can specify the label for a field by using the 'label' argument to a Field
  1421. # class. If you don't specify 'label', Django will use the field name with
  1422. # underscores converted to spaces, and the initial letter capitalized.
  1423. class UserRegistration(Form):
  1424. username = CharField(max_length=10, label='Your username')
  1425. password1 = CharField(widget=PasswordInput)
  1426. password2 = CharField(widget=PasswordInput, label='Contraseña (de nuevo)')
  1427. p = UserRegistration(auto_id=False)
  1428. self.assertHTMLEqual(
  1429. p.as_ul(),
  1430. """<li>Your username: <input type="text" name="username" maxlength="10" required /></li>
  1431. <li>Password1: <input type="password" name="password1" required /></li>
  1432. <li>Contraseña (de nuevo): <input type="password" name="password2" required /></li>"""
  1433. )
  1434. # Labels for as_* methods will only end in a colon if they don't end in other
  1435. # punctuation already.
  1436. class Questions(Form):
  1437. q1 = CharField(label='The first question')
  1438. q2 = CharField(label='What is your name?')
  1439. q3 = CharField(label='The answer to life is:')
  1440. q4 = CharField(label='Answer this question!')
  1441. q5 = CharField(label='The last question. Period.')
  1442. self.assertHTMLEqual(
  1443. Questions(auto_id=False).as_p(),
  1444. """<p>The first question: <input type="text" name="q1" required /></p>
  1445. <p>What is your name? <input type="text" name="q2" required /></p>
  1446. <p>The answer to life is: <input type="text" name="q3" required /></p>
  1447. <p>Answer this question! <input type="text" name="q4" required /></p>
  1448. <p>The last question. Period. <input type="text" name="q5" required /></p>"""
  1449. )
  1450. self.assertHTMLEqual(
  1451. Questions().as_p(),
  1452. """<p><label for="id_q1">The first question:</label> <input type="text" name="q1" id="id_q1" required /></p>
  1453. <p><label for="id_q2">What is your name?</label> <input type="text" name="q2" id="id_q2" required /></p>
  1454. <p><label for="id_q3">The answer to life is:</label> <input type="text" name="q3" id="id_q3" required /></p>
  1455. <p><label for="id_q4">Answer this question!</label> <input type="text" name="q4" id="id_q4" required /></p>
  1456. <p><label for="id_q5">The last question. Period.</label> <input type="text" name="q5" id="id_q5" required /></p>"""
  1457. )
  1458. # If a label is set to the empty string for a field, that field won't get a label.
  1459. class UserRegistration(Form):
  1460. username = CharField(max_length=10, label='')
  1461. password = CharField(widget=PasswordInput)
  1462. p = UserRegistration(auto_id=False)
  1463. self.assertHTMLEqual(p.as_ul(), """<li> <input type="text" name="username" maxlength="10" required /></li>
  1464. <li>Password: <input type="password" name="password" required /></li>""")
  1465. p = UserRegistration(auto_id='id_%s')
  1466. self.assertHTMLEqual(
  1467. p.as_ul(),
  1468. """<li> <input id="id_username" type="text" name="username" maxlength="10" required /></li>
  1469. <li><label for="id_password">Password:</label>
  1470. <input type="password" name="password" id="id_password" required /></li>"""
  1471. )
  1472. # If label is None, Django will auto-create the label from the field name. This
  1473. # is default behavior.
  1474. class UserRegistration(Form):
  1475. username = CharField(max_length=10, label=None)
  1476. password = CharField(widget=PasswordInput)
  1477. p = UserRegistration(auto_id=False)
  1478. self.assertHTMLEqual(
  1479. p.as_ul(),
  1480. """<li>Username: <input type="text" name="username" maxlength="10" required /></li>
  1481. <li>Password: <input type="password" name="password" required /></li>"""
  1482. )
  1483. p = UserRegistration(auto_id='id_%s')
  1484. self.assertHTMLEqual(
  1485. p.as_ul(),
  1486. """<li><label for="id_username">Username:</label>
  1487. <input id="id_username" type="text" name="username" maxlength="10" required /></li>
  1488. <li><label for="id_password">Password:</label>
  1489. <input type="password" name="password" id="id_password" required /></li>"""
  1490. )
  1491. def test_label_suffix(self):
  1492. # You can specify the 'label_suffix' argument to a Form class to modify the
  1493. # punctuation symbol used at the end of a label. By default, the colon (:) is
  1494. # used, and is only appended to the label if the label doesn't already end with a
  1495. # punctuation symbol: ., !, ? or :. If you specify a different suffix, it will
  1496. # be appended regardless of the last character of the label.
  1497. class FavoriteForm(Form):
  1498. color = CharField(label='Favorite color?')
  1499. animal = CharField(label='Favorite animal')
  1500. answer = CharField(label='Secret answer', label_suffix=' =')
  1501. f = FavoriteForm(auto_id=False)
  1502. self.assertHTMLEqual(f.as_ul(), """<li>Favorite color? <input type="text" name="color" required /></li>
  1503. <li>Favorite animal: <input type="text" name="animal" required /></li>
  1504. <li>Secret answer = <input type="text" name="answer" required /></li>""")
  1505. f = FavoriteForm(auto_id=False, label_suffix='?')
  1506. self.assertHTMLEqual(f.as_ul(), """<li>Favorite color? <input type="text" name="color" required /></li>
  1507. <li>Favorite animal? <input type="text" name="animal" required /></li>
  1508. <li>Secret answer = <input type="text" name="answer" required /></li>""")
  1509. f = FavoriteForm(auto_id=False, label_suffix='')
  1510. self.assertHTMLEqual(f.as_ul(), """<li>Favorite color? <input type="text" name="color" required /></li>
  1511. <li>Favorite animal <input type="text" name="animal" required /></li>
  1512. <li>Secret answer = <input type="text" name="answer" required /></li>""")
  1513. f = FavoriteForm(auto_id=False, label_suffix='\u2192')
  1514. self.assertHTMLEqual(
  1515. f.as_ul(),
  1516. '<li>Favorite color? <input type="text" name="color" required /></li>\n'
  1517. '<li>Favorite animal\u2192 <input type="text" name="animal" required /></li>\n'
  1518. '<li>Secret answer = <input type="text" name="answer" required /></li>'
  1519. )
  1520. def test_initial_data(self):
  1521. # You can specify initial data for a field by using the 'initial' argument to a
  1522. # Field class. This initial data is displayed when a Form is rendered with *no*
  1523. # data. It is not displayed when a Form is rendered with any data (including an
  1524. # empty dictionary). Also, the initial value is *not* used if data for a
  1525. # particular required field isn't provided.
  1526. class UserRegistration(Form):
  1527. username = CharField(max_length=10, initial='django')
  1528. password = CharField(widget=PasswordInput)
  1529. # Here, we're not submitting any data, so the initial value will be displayed.)
  1530. p = UserRegistration(auto_id=False)
  1531. self.assertHTMLEqual(
  1532. p.as_ul(),
  1533. """<li>Username: <input type="text" name="username" value="django" maxlength="10" required /></li>
  1534. <li>Password: <input type="password" name="password" required /></li>"""
  1535. )
  1536. # Here, we're submitting data, so the initial value will *not* be displayed.
  1537. p = UserRegistration({}, auto_id=False)
  1538. self.assertHTMLEqual(
  1539. p.as_ul(),
  1540. """<li><ul class="errorlist"><li>This field is required.</li></ul>
  1541. Username: <input type="text" name="username" maxlength="10" required /></li>
  1542. <li><ul class="errorlist"><li>This field is required.</li></ul>
  1543. Password: <input type="password" name="password" required /></li>"""
  1544. )
  1545. p = UserRegistration({'username': ''}, auto_id=False)
  1546. self.assertHTMLEqual(
  1547. p.as_ul(),
  1548. """<li><ul class="errorlist"><li>This field is required.</li></ul>
  1549. Username: <input type="text" name="username" maxlength="10" required /></li>
  1550. <li><ul class="errorlist"><li>This field is required.</li></ul>
  1551. Password: <input type="password" name="password" required /></li>"""
  1552. )
  1553. p = UserRegistration({'username': 'foo'}, auto_id=False)
  1554. self.assertHTMLEqual(
  1555. p.as_ul(),
  1556. """<li>Username: <input type="text" name="username" value="foo" maxlength="10" required /></li>
  1557. <li><ul class="errorlist"><li>This field is required.</li></ul>
  1558. Password: <input type="password" name="password" required /></li>"""
  1559. )
  1560. # An 'initial' value is *not* used as a fallback if data is not provided. In this
  1561. # example, we don't provide a value for 'username', and the form raises a
  1562. # validation error rather than using the initial value for 'username'.
  1563. p = UserRegistration({'password': 'secret'})
  1564. self.assertEqual(p.errors['username'], ['This field is required.'])
  1565. self.assertFalse(p.is_valid())
  1566. def test_dynamic_initial_data(self):
  1567. # The previous technique dealt with "hard-coded" initial data, but it's also
  1568. # possible to specify initial data after you've already created the Form class
  1569. # (i.e., at runtime). Use the 'initial' parameter to the Form constructor. This
  1570. # should be a dictionary containing initial values for one or more fields in the
  1571. # form, keyed by field name.
  1572. class UserRegistration(Form):
  1573. username = CharField(max_length=10)
  1574. password = CharField(widget=PasswordInput)
  1575. # Here, we're not submitting any data, so the initial value will be displayed.)
  1576. p = UserRegistration(initial={'username': 'django'}, auto_id=False)
  1577. self.assertHTMLEqual(
  1578. p.as_ul(),
  1579. """<li>Username: <input type="text" name="username" value="django" maxlength="10" required /></li>
  1580. <li>Password: <input type="password" name="password" required /></li>"""
  1581. )
  1582. p = UserRegistration(initial={'username': 'stephane'}, auto_id=False)
  1583. self.assertHTMLEqual(
  1584. p.as_ul(),
  1585. """<li>Username: <input type="text" name="username" value="stephane" maxlength="10" required /></li>
  1586. <li>Password: <input type="password" name="password" required /></li>"""
  1587. )
  1588. # The 'initial' parameter is meaningless if you pass data.
  1589. p = UserRegistration({}, initial={'username': 'django'}, auto_id=False)
  1590. self.assertHTMLEqual(
  1591. p.as_ul(),
  1592. """<li><ul class="errorlist"><li>This field is required.</li></ul>
  1593. Username: <input type="text" name="username" maxlength="10" required /></li>
  1594. <li><ul class="errorlist"><li>This field is required.</li></ul>
  1595. Password: <input type="password" name="password" required /></li>"""
  1596. )
  1597. p = UserRegistration({'username': ''}, initial={'username': 'django'}, auto_id=False)
  1598. self.assertHTMLEqual(
  1599. p.as_ul(),
  1600. """<li><ul class="errorlist"><li>This field is required.</li></ul>
  1601. Username: <input type="text" name="username" maxlength="10" required /></li>
  1602. <li><ul class="errorlist"><li>This field is required.</li></ul>
  1603. Password: <input type="password" name="password" required /></li>"""
  1604. )
  1605. p = UserRegistration({'username': 'foo'}, initial={'username': 'django'}, auto_id=False)
  1606. self.assertHTMLEqual(
  1607. p.as_ul(), """<li>Username: <input type="text" name="username" value="foo" maxlength="10" required /></li>
  1608. <li><ul class="errorlist"><li>This field is required.</li></ul>
  1609. Password: <input type="password" name="password" required /></li>"""
  1610. )
  1611. # A dynamic 'initial' value is *not* used as a fallback if data is not provided.
  1612. # In this example, we don't provide a value for 'username', and the form raises a
  1613. # validation error rather than using the initial value for 'username'.
  1614. p = UserRegistration({'password': 'secret'}, initial={'username': 'django'})
  1615. self.assertEqual(p.errors['username'], ['This field is required.'])
  1616. self.assertFalse(p.is_valid())
  1617. # If a Form defines 'initial' *and* 'initial' is passed as a parameter to Form(),
  1618. # then the latter will get precedence.
  1619. class UserRegistration(Form):
  1620. username = CharField(max_length=10, initial='django')
  1621. password = CharField(widget=PasswordInput)
  1622. p = UserRegistration(initial={'username': 'babik'}, auto_id=False)
  1623. self.assertHTMLEqual(
  1624. p.as_ul(),
  1625. """<li>Username: <input type="text" name="username" value="babik" maxlength="10" required /></li>
  1626. <li>Password: <input type="password" name="password" required /></li>"""
  1627. )
  1628. def test_callable_initial_data(self):
  1629. # The previous technique dealt with raw values as initial data, but it's also
  1630. # possible to specify callable data.
  1631. class UserRegistration(Form):
  1632. username = CharField(max_length=10)
  1633. password = CharField(widget=PasswordInput)
  1634. options = MultipleChoiceField(choices=[('f', 'foo'), ('b', 'bar'), ('w', 'whiz')])
  1635. # We need to define functions that get called later.)
  1636. def initial_django():
  1637. return 'django'
  1638. def initial_stephane():
  1639. return 'stephane'
  1640. def initial_options():
  1641. return ['f', 'b']
  1642. def initial_other_options():
  1643. return ['b', 'w']
  1644. # Here, we're not submitting any data, so the initial value will be displayed.)
  1645. p = UserRegistration(initial={'username': initial_django, 'options': initial_options}, auto_id=False)
  1646. self.assertHTMLEqual(
  1647. p.as_ul(),
  1648. """<li>Username: <input type="text" name="username" value="django" maxlength="10" required /></li>
  1649. <li>Password: <input type="password" name="password" required /></li>
  1650. <li>Options: <select multiple="multiple" name="options" required>
  1651. <option value="f" selected>foo</option>
  1652. <option value="b" selected>bar</option>
  1653. <option value="w">whiz</option>
  1654. </select></li>"""
  1655. )
  1656. # The 'initial' parameter is meaningless if you pass data.
  1657. p = UserRegistration({}, initial={'username': initial_django, 'options': initial_options}, auto_id=False)
  1658. self.assertHTMLEqual(
  1659. p.as_ul(),
  1660. """<li><ul class="errorlist"><li>This field is required.</li></ul>
  1661. Username: <input type="text" name="username" maxlength="10" required /></li>
  1662. <li><ul class="errorlist"><li>This field is required.</li></ul>
  1663. Password: <input type="password" name="password" required /></li>
  1664. <li><ul class="errorlist"><li>This field is required.</li></ul>
  1665. Options: <select multiple="multiple" name="options" required>
  1666. <option value="f">foo</option>
  1667. <option value="b">bar</option>
  1668. <option value="w">whiz</option>
  1669. </select></li>"""
  1670. )
  1671. p = UserRegistration({'username': ''}, initial={'username': initial_django}, auto_id=False)
  1672. self.assertHTMLEqual(
  1673. p.as_ul(),
  1674. """<li><ul class="errorlist"><li>This field is required.</li></ul>
  1675. Username: <input type="text" name="username" maxlength="10" required /></li>
  1676. <li><ul class="errorlist"><li>This field is required.</li></ul>
  1677. Password: <input type="password" name="password" required /></li>
  1678. <li><ul class="errorlist"><li>This field is required.</li></ul>
  1679. Options: <select multiple="multiple" name="options" required>
  1680. <option value="f">foo</option>
  1681. <option value="b">bar</option>
  1682. <option value="w">whiz</option>
  1683. </select></li>"""
  1684. )
  1685. p = UserRegistration(
  1686. {'username': 'foo', 'options': ['f', 'b']}, initial={'username': initial_django}, auto_id=False
  1687. )
  1688. self.assertHTMLEqual(
  1689. p.as_ul(),
  1690. """<li>Username: <input type="text" name="username" value="foo" maxlength="10" required /></li>
  1691. <li><ul class="errorlist"><li>This field is required.</li></ul>
  1692. Password: <input type="password" name="password" required /></li>
  1693. <li>Options: <select multiple="multiple" name="options" required>
  1694. <option value="f" selected>foo</option>
  1695. <option value="b" selected>bar</option>
  1696. <option value="w">whiz</option>
  1697. </select></li>"""
  1698. )
  1699. # A callable 'initial' value is *not* used as a fallback if data is not provided.
  1700. # In this example, we don't provide a value for 'username', and the form raises a
  1701. # validation error rather than using the initial value for 'username'.
  1702. p = UserRegistration({'password': 'secret'}, initial={'username': initial_django, 'options': initial_options})
  1703. self.assertEqual(p.errors['username'], ['This field is required.'])
  1704. self.assertFalse(p.is_valid())
  1705. # If a Form defines 'initial' *and* 'initial' is passed as a parameter to Form(),
  1706. # then the latter will get precedence.
  1707. class UserRegistration(Form):
  1708. username = CharField(max_length=10, initial=initial_django)
  1709. password = CharField(widget=PasswordInput)
  1710. options = MultipleChoiceField(
  1711. choices=[('f', 'foo'), ('b', 'bar'), ('w', 'whiz')],
  1712. initial=initial_other_options,
  1713. )
  1714. p = UserRegistration(auto_id=False)
  1715. self.assertHTMLEqual(
  1716. p.as_ul(),
  1717. """<li>Username: <input type="text" name="username" value="django" maxlength="10" required /></li>
  1718. <li>Password: <input type="password" name="password" required /></li>
  1719. <li>Options: <select multiple="multiple" name="options" required>
  1720. <option value="f">foo</option>
  1721. <option value="b" selected>bar</option>
  1722. <option value="w" selected>whiz</option>
  1723. </select></li>"""
  1724. )
  1725. p = UserRegistration(initial={'username': initial_stephane, 'options': initial_options}, auto_id=False)
  1726. self.assertHTMLEqual(
  1727. p.as_ul(),
  1728. """<li>Username: <input type="text" name="username" value="stephane" maxlength="10" required /></li>
  1729. <li>Password: <input type="password" name="password" required /></li>
  1730. <li>Options: <select multiple="multiple" name="options" required>
  1731. <option value="f" selected>foo</option>
  1732. <option value="b" selected>bar</option>
  1733. <option value="w">whiz</option>
  1734. </select></li>"""
  1735. )
  1736. def test_get_initial_for_field(self):
  1737. class PersonForm(Form):
  1738. first_name = CharField(initial='John')
  1739. last_name = CharField(initial='Doe')
  1740. age = IntegerField()
  1741. occupation = CharField(initial=lambda: 'Unknown')
  1742. form = PersonForm(initial={'first_name': 'Jane'})
  1743. self.assertEqual(form.get_initial_for_field(form.fields['age'], 'age'), None)
  1744. self.assertEqual(form.get_initial_for_field(form.fields['last_name'], 'last_name'), 'Doe')
  1745. # Form.initial overrides Field.initial.
  1746. self.assertEqual(form.get_initial_for_field(form.fields['first_name'], 'first_name'), 'Jane')
  1747. # Callables are evaluated.
  1748. self.assertEqual(form.get_initial_for_field(form.fields['occupation'], 'occupation'), 'Unknown')
  1749. def test_changed_data(self):
  1750. class Person(Form):
  1751. first_name = CharField(initial='Hans')
  1752. last_name = CharField(initial='Greatel')
  1753. birthday = DateField(initial=datetime.date(1974, 8, 16))
  1754. p = Person(data={'first_name': 'Hans', 'last_name': 'Scrmbl', 'birthday': '1974-08-16'})
  1755. self.assertTrue(p.is_valid())
  1756. self.assertNotIn('first_name', p.changed_data)
  1757. self.assertIn('last_name', p.changed_data)
  1758. self.assertNotIn('birthday', p.changed_data)
  1759. # A field raising ValidationError is always in changed_data
  1760. class PedanticField(forms.Field):
  1761. def to_python(self, value):
  1762. raise ValidationError('Whatever')
  1763. class Person2(Person):
  1764. pedantic = PedanticField(initial='whatever', show_hidden_initial=True)
  1765. p = Person2(data={
  1766. 'first_name': 'Hans', 'last_name': 'Scrmbl', 'birthday': '1974-08-16',
  1767. 'initial-pedantic': 'whatever',
  1768. })
  1769. self.assertFalse(p.is_valid())
  1770. self.assertIn('pedantic', p.changed_data)
  1771. def test_boundfield_values(self):
  1772. # It's possible to get to the value which would be used for rendering
  1773. # the widget for a field by using the BoundField's value method.
  1774. class UserRegistration(Form):
  1775. username = CharField(max_length=10, initial='djangonaut')
  1776. password = CharField(widget=PasswordInput)
  1777. unbound = UserRegistration()
  1778. bound = UserRegistration({'password': 'foo'})
  1779. self.assertIsNone(bound['username'].value())
  1780. self.assertEqual(unbound['username'].value(), 'djangonaut')
  1781. self.assertEqual(bound['password'].value(), 'foo')
  1782. self.assertIsNone(unbound['password'].value())
  1783. def test_boundfield_initial_called_once(self):
  1784. """
  1785. Multiple calls to BoundField().value() in an unbound form should return
  1786. the same result each time (#24391).
  1787. """
  1788. class MyForm(Form):
  1789. name = CharField(max_length=10, initial=uuid.uuid4)
  1790. form = MyForm()
  1791. name = form['name']
  1792. self.assertEqual(name.value(), name.value())
  1793. # BoundField is also cached
  1794. self.assertIs(form['name'], name)
  1795. def test_boundfield_value_disabled_callable_initial(self):
  1796. class PersonForm(Form):
  1797. name = CharField(initial=lambda: 'John Doe', disabled=True)
  1798. # Without form data.
  1799. form = PersonForm()
  1800. self.assertEqual(form['name'].value(), 'John Doe')
  1801. # With form data. As the field is disabled, the value should not be
  1802. # affected by the form data.
  1803. form = PersonForm({})
  1804. self.assertEqual(form['name'].value(), 'John Doe')
  1805. def test_boundfield_rendering(self):
  1806. """
  1807. Python 2 issue: Rendering a BoundField with bytestring content
  1808. doesn't lose it's safe string status (#22950).
  1809. """
  1810. class CustomWidget(TextInput):
  1811. def render(self, name, value, attrs=None, choices=None,
  1812. renderer=None, extra_context=None):
  1813. return format_html(str('<input{} />'), ' id=custom')
  1814. class SampleForm(Form):
  1815. name = CharField(widget=CustomWidget)
  1816. f = SampleForm(data={'name': 'bar'})
  1817. self.assertIsInstance(force_text(f['name']), SafeData)
  1818. def test_custom_boundfield(self):
  1819. class CustomField(CharField):
  1820. def get_bound_field(self, form, name):
  1821. return (form, name)
  1822. class SampleForm(Form):
  1823. name = CustomField()
  1824. f = SampleForm()
  1825. self.assertEqual(f['name'], (f, 'name'))
  1826. def test_initial_datetime_values(self):
  1827. now = datetime.datetime.now()
  1828. # Nix microseconds (since they should be ignored). #22502
  1829. now_no_ms = now.replace(microsecond=0)
  1830. if now == now_no_ms:
  1831. now = now.replace(microsecond=1)
  1832. def delayed_now():
  1833. return now
  1834. def delayed_now_time():
  1835. return now.time()
  1836. class HiddenInputWithoutMicrosec(HiddenInput):
  1837. supports_microseconds = False
  1838. class TextInputWithoutMicrosec(TextInput):
  1839. supports_microseconds = False
  1840. class DateTimeForm(Form):
  1841. auto_timestamp = DateTimeField(initial=delayed_now)
  1842. auto_time_only = TimeField(initial=delayed_now_time)
  1843. supports_microseconds = DateTimeField(initial=delayed_now, widget=TextInput)
  1844. hi_default_microsec = DateTimeField(initial=delayed_now, widget=HiddenInput)
  1845. hi_without_microsec = DateTimeField(initial=delayed_now, widget=HiddenInputWithoutMicrosec)
  1846. ti_without_microsec = DateTimeField(initial=delayed_now, widget=TextInputWithoutMicrosec)
  1847. unbound = DateTimeForm()
  1848. self.assertEqual(unbound['auto_timestamp'].value(), now_no_ms)
  1849. self.assertEqual(unbound['auto_time_only'].value(), now_no_ms.time())
  1850. self.assertEqual(unbound['supports_microseconds'].value(), now)
  1851. self.assertEqual(unbound['hi_default_microsec'].value(), now)
  1852. self.assertEqual(unbound['hi_without_microsec'].value(), now_no_ms)
  1853. self.assertEqual(unbound['ti_without_microsec'].value(), now_no_ms)
  1854. def test_datetime_clean_initial_callable_disabled(self):
  1855. now = datetime.datetime(2006, 10, 25, 14, 30, 45, 123456)
  1856. class DateTimeForm(forms.Form):
  1857. dt = DateTimeField(initial=lambda: now, disabled=True)
  1858. form = DateTimeForm({})
  1859. self.assertEqual(form.errors, {})
  1860. self.assertEqual(form.cleaned_data, {'dt': now})
  1861. def test_datetime_changed_data_callable_with_microseconds(self):
  1862. class DateTimeForm(forms.Form):
  1863. dt = DateTimeField(initial=lambda: datetime.datetime(2006, 10, 25, 14, 30, 45, 123456), disabled=True)
  1864. form = DateTimeForm({'dt': '2006-10-25 14:30:45'})
  1865. self.assertEqual(form.changed_data, [])
  1866. def test_help_text(self):
  1867. # You can specify descriptive text for a field by using the 'help_text' argument)
  1868. class UserRegistration(Form):
  1869. username = CharField(max_length=10, help_text='e.g., user@example.com')
  1870. password = CharField(widget=PasswordInput, help_text='Wählen Sie mit Bedacht.')
  1871. p = UserRegistration(auto_id=False)
  1872. self.assertHTMLEqual(
  1873. p.as_ul(),
  1874. """<li>Username: <input type="text" name="username" maxlength="10" required />
  1875. <span class="helptext">e.g., user@example.com</span></li>
  1876. <li>Password: <input type="password" name="password" required />
  1877. <span class="helptext">Wählen Sie mit Bedacht.</span></li>"""
  1878. )
  1879. self.assertHTMLEqual(
  1880. p.as_p(),
  1881. """<p>Username: <input type="text" name="username" maxlength="10" required />
  1882. <span class="helptext">e.g., user@example.com</span></p>
  1883. <p>Password: <input type="password" name="password" required />
  1884. <span class="helptext">Wählen Sie mit Bedacht.</span></p>"""
  1885. )
  1886. self.assertHTMLEqual(
  1887. p.as_table(),
  1888. """<tr><th>Username:</th><td><input type="text" name="username" maxlength="10" required /><br />
  1889. <span class="helptext">e.g., user@example.com</span></td></tr>
  1890. <tr><th>Password:</th><td><input type="password" name="password" required /><br />
  1891. <span class="helptext">Wählen Sie mit Bedacht.</span></td></tr>"""
  1892. )
  1893. # The help text is displayed whether or not data is provided for the form.
  1894. p = UserRegistration({'username': 'foo'}, auto_id=False)
  1895. self.assertHTMLEqual(
  1896. p.as_ul(),
  1897. """<li>Username: <input type="text" name="username" value="foo" maxlength="10" required />
  1898. <span class="helptext">e.g., user@example.com</span></li>
  1899. <li><ul class="errorlist"><li>This field is required.</li></ul>
  1900. Password: <input type="password" name="password" required />
  1901. <span class="helptext">Wählen Sie mit Bedacht.</span></li>"""
  1902. )
  1903. # help_text is not displayed for hidden fields. It can be used for documentation
  1904. # purposes, though.
  1905. class UserRegistration(Form):
  1906. username = CharField(max_length=10, help_text='e.g., user@example.com')
  1907. password = CharField(widget=PasswordInput)
  1908. next = CharField(widget=HiddenInput, initial='/', help_text='Redirect destination')
  1909. p = UserRegistration(auto_id=False)
  1910. self.assertHTMLEqual(
  1911. p.as_ul(),
  1912. """<li>Username: <input type="text" name="username" maxlength="10" required />
  1913. <span class="helptext">e.g., user@example.com</span></li>
  1914. <li>Password: <input type="password" name="password" required />
  1915. <input type="hidden" name="next" value="/" /></li>"""
  1916. )
  1917. def test_subclassing_forms(self):
  1918. # You can subclass a Form to add fields. The resulting form subclass will have
  1919. # all of the fields of the parent Form, plus whichever fields you define in the
  1920. # subclass.
  1921. class Person(Form):
  1922. first_name = CharField()
  1923. last_name = CharField()
  1924. birthday = DateField()
  1925. class Musician(Person):
  1926. instrument = CharField()
  1927. p = Person(auto_id=False)
  1928. self.assertHTMLEqual(
  1929. p.as_ul(),
  1930. """<li>First name: <input type="text" name="first_name" required /></li>
  1931. <li>Last name: <input type="text" name="last_name" required /></li>
  1932. <li>Birthday: <input type="text" name="birthday" required /></li>"""
  1933. )
  1934. m = Musician(auto_id=False)
  1935. self.assertHTMLEqual(
  1936. m.as_ul(),
  1937. """<li>First name: <input type="text" name="first_name" required /></li>
  1938. <li>Last name: <input type="text" name="last_name" required /></li>
  1939. <li>Birthday: <input type="text" name="birthday" required /></li>
  1940. <li>Instrument: <input type="text" name="instrument" required /></li>"""
  1941. )
  1942. # Yes, you can subclass multiple forms. The fields are added in the order in
  1943. # which the parent classes are listed.
  1944. class Person(Form):
  1945. first_name = CharField()
  1946. last_name = CharField()
  1947. birthday = DateField()
  1948. class Instrument(Form):
  1949. instrument = CharField()
  1950. class Beatle(Person, Instrument):
  1951. haircut_type = CharField()
  1952. b = Beatle(auto_id=False)
  1953. self.assertHTMLEqual(b.as_ul(), """<li>Instrument: <input type="text" name="instrument" required /></li>
  1954. <li>First name: <input type="text" name="first_name" required /></li>
  1955. <li>Last name: <input type="text" name="last_name" required /></li>
  1956. <li>Birthday: <input type="text" name="birthday" required /></li>
  1957. <li>Haircut type: <input type="text" name="haircut_type" required /></li>""")
  1958. def test_forms_with_prefixes(self):
  1959. # Sometimes it's necessary to have multiple forms display on the same HTML page,
  1960. # or multiple copies of the same form. We can accomplish this with form prefixes.
  1961. # Pass the keyword argument 'prefix' to the Form constructor to use this feature.
  1962. # This value will be prepended to each HTML form field name. One way to think
  1963. # about this is "namespaces for HTML forms". Notice that in the data argument,
  1964. # each field's key has the prefix, in this case 'person1', prepended to the
  1965. # actual field name.
  1966. class Person(Form):
  1967. first_name = CharField()
  1968. last_name = CharField()
  1969. birthday = DateField()
  1970. data = {
  1971. 'person1-first_name': 'John',
  1972. 'person1-last_name': 'Lennon',
  1973. 'person1-birthday': '1940-10-9'
  1974. }
  1975. p = Person(data, prefix='person1')
  1976. self.assertHTMLEqual(
  1977. p.as_ul(),
  1978. """<li><label for="id_person1-first_name">First name:</label>
  1979. <input type="text" name="person1-first_name" value="John" id="id_person1-first_name" required /></li>
  1980. <li><label for="id_person1-last_name">Last name:</label>
  1981. <input type="text" name="person1-last_name" value="Lennon" id="id_person1-last_name" required /></li>
  1982. <li><label for="id_person1-birthday">Birthday:</label>
  1983. <input type="text" name="person1-birthday" value="1940-10-9" id="id_person1-birthday" required /></li>"""
  1984. )
  1985. self.assertHTMLEqual(
  1986. str(p['first_name']),
  1987. '<input type="text" name="person1-first_name" value="John" id="id_person1-first_name" required />'
  1988. )
  1989. self.assertHTMLEqual(
  1990. str(p['last_name']),
  1991. '<input type="text" name="person1-last_name" value="Lennon" id="id_person1-last_name" required />'
  1992. )
  1993. self.assertHTMLEqual(
  1994. str(p['birthday']),
  1995. '<input type="text" name="person1-birthday" value="1940-10-9" id="id_person1-birthday" required />'
  1996. )
  1997. self.assertEqual(p.errors, {})
  1998. self.assertTrue(p.is_valid())
  1999. self.assertEqual(p.cleaned_data['first_name'], 'John')
  2000. self.assertEqual(p.cleaned_data['last_name'], 'Lennon')
  2001. self.assertEqual(p.cleaned_data['birthday'], datetime.date(1940, 10, 9))
  2002. # Let's try submitting some bad data to make sure form.errors and field.errors
  2003. # work as expected.
  2004. data = {
  2005. 'person1-first_name': '',
  2006. 'person1-last_name': '',
  2007. 'person1-birthday': ''
  2008. }
  2009. p = Person(data, prefix='person1')
  2010. self.assertEqual(p.errors['first_name'], ['This field is required.'])
  2011. self.assertEqual(p.errors['last_name'], ['This field is required.'])
  2012. self.assertEqual(p.errors['birthday'], ['This field is required.'])
  2013. self.assertEqual(p['first_name'].errors, ['This field is required.'])
  2014. # Accessing a nonexistent field.
  2015. with self.assertRaises(KeyError):
  2016. p['person1-first_name'].errors
  2017. # In this example, the data doesn't have a prefix, but the form requires it, so
  2018. # the form doesn't "see" the fields.
  2019. data = {
  2020. 'first_name': 'John',
  2021. 'last_name': 'Lennon',
  2022. 'birthday': '1940-10-9'
  2023. }
  2024. p = Person(data, prefix='person1')
  2025. self.assertEqual(p.errors['first_name'], ['This field is required.'])
  2026. self.assertEqual(p.errors['last_name'], ['This field is required.'])
  2027. self.assertEqual(p.errors['birthday'], ['This field is required.'])
  2028. # With prefixes, a single data dictionary can hold data for multiple instances
  2029. # of the same form.
  2030. data = {
  2031. 'person1-first_name': 'John',
  2032. 'person1-last_name': 'Lennon',
  2033. 'person1-birthday': '1940-10-9',
  2034. 'person2-first_name': 'Jim',
  2035. 'person2-last_name': 'Morrison',
  2036. 'person2-birthday': '1943-12-8'
  2037. }
  2038. p1 = Person(data, prefix='person1')
  2039. self.assertTrue(p1.is_valid())
  2040. self.assertEqual(p1.cleaned_data['first_name'], 'John')
  2041. self.assertEqual(p1.cleaned_data['last_name'], 'Lennon')
  2042. self.assertEqual(p1.cleaned_data['birthday'], datetime.date(1940, 10, 9))
  2043. p2 = Person(data, prefix='person2')
  2044. self.assertTrue(p2.is_valid())
  2045. self.assertEqual(p2.cleaned_data['first_name'], 'Jim')
  2046. self.assertEqual(p2.cleaned_data['last_name'], 'Morrison')
  2047. self.assertEqual(p2.cleaned_data['birthday'], datetime.date(1943, 12, 8))
  2048. # By default, forms append a hyphen between the prefix and the field name, but a
  2049. # form can alter that behavior by implementing the add_prefix() method. This
  2050. # method takes a field name and returns the prefixed field, according to
  2051. # self.prefix.
  2052. class Person(Form):
  2053. first_name = CharField()
  2054. last_name = CharField()
  2055. birthday = DateField()
  2056. def add_prefix(self, field_name):
  2057. return '%s-prefix-%s' % (self.prefix, field_name) if self.prefix else field_name
  2058. p = Person(prefix='foo')
  2059. self.assertHTMLEqual(
  2060. p.as_ul(),
  2061. """<li><label for="id_foo-prefix-first_name">First name:</label>
  2062. <input type="text" name="foo-prefix-first_name" id="id_foo-prefix-first_name" required /></li>
  2063. <li><label for="id_foo-prefix-last_name">Last name:</label>
  2064. <input type="text" name="foo-prefix-last_name" id="id_foo-prefix-last_name" required /></li>
  2065. <li><label for="id_foo-prefix-birthday">Birthday:</label>
  2066. <input type="text" name="foo-prefix-birthday" id="id_foo-prefix-birthday" required /></li>"""
  2067. )
  2068. data = {
  2069. 'foo-prefix-first_name': 'John',
  2070. 'foo-prefix-last_name': 'Lennon',
  2071. 'foo-prefix-birthday': '1940-10-9'
  2072. }
  2073. p = Person(data, prefix='foo')
  2074. self.assertTrue(p.is_valid())
  2075. self.assertEqual(p.cleaned_data['first_name'], 'John')
  2076. self.assertEqual(p.cleaned_data['last_name'], 'Lennon')
  2077. self.assertEqual(p.cleaned_data['birthday'], datetime.date(1940, 10, 9))
  2078. def test_class_prefix(self):
  2079. # Prefix can be also specified at the class level.
  2080. class Person(Form):
  2081. first_name = CharField()
  2082. prefix = 'foo'
  2083. p = Person()
  2084. self.assertEqual(p.prefix, 'foo')
  2085. p = Person(prefix='bar')
  2086. self.assertEqual(p.prefix, 'bar')
  2087. def test_forms_with_null_boolean(self):
  2088. # NullBooleanField is a bit of a special case because its presentation (widget)
  2089. # is different than its data. This is handled transparently, though.
  2090. class Person(Form):
  2091. name = CharField()
  2092. is_cool = NullBooleanField()
  2093. p = Person({'name': 'Joe'}, auto_id=False)
  2094. self.assertHTMLEqual(str(p['is_cool']), """<select name="is_cool" required>
  2095. <option value="1" selected>Unknown</option>
  2096. <option value="2">Yes</option>
  2097. <option value="3">No</option>
  2098. </select>""")
  2099. p = Person({'name': 'Joe', 'is_cool': '1'}, auto_id=False)
  2100. self.assertHTMLEqual(str(p['is_cool']), """<select name="is_cool" required>
  2101. <option value="1" selected>Unknown</option>
  2102. <option value="2">Yes</option>
  2103. <option value="3">No</option>
  2104. </select>""")
  2105. p = Person({'name': 'Joe', 'is_cool': '2'}, auto_id=False)
  2106. self.assertHTMLEqual(str(p['is_cool']), """<select name="is_cool" required>
  2107. <option value="1">Unknown</option>
  2108. <option value="2" selected>Yes</option>
  2109. <option value="3">No</option>
  2110. </select>""")
  2111. p = Person({'name': 'Joe', 'is_cool': '3'}, auto_id=False)
  2112. self.assertHTMLEqual(str(p['is_cool']), """<select name="is_cool" required>
  2113. <option value="1">Unknown</option>
  2114. <option value="2">Yes</option>
  2115. <option value="3" selected>No</option>
  2116. </select>""")
  2117. p = Person({'name': 'Joe', 'is_cool': True}, auto_id=False)
  2118. self.assertHTMLEqual(str(p['is_cool']), """<select name="is_cool" required>
  2119. <option value="1">Unknown</option>
  2120. <option value="2" selected>Yes</option>
  2121. <option value="3">No</option>
  2122. </select>""")
  2123. p = Person({'name': 'Joe', 'is_cool': False}, auto_id=False)
  2124. self.assertHTMLEqual(str(p['is_cool']), """<select name="is_cool" required>
  2125. <option value="1">Unknown</option>
  2126. <option value="2">Yes</option>
  2127. <option value="3" selected>No</option>
  2128. </select>""")
  2129. def test_forms_with_file_fields(self):
  2130. # FileFields are a special case because they take their data from the request.FILES,
  2131. # not request.POST.
  2132. class FileForm(Form):
  2133. file1 = FileField()
  2134. f = FileForm(auto_id=False)
  2135. self.assertHTMLEqual(
  2136. f.as_table(),
  2137. '<tr><th>File1:</th><td><input type="file" name="file1" required /></td></tr>',
  2138. )
  2139. f = FileForm(data={}, files={}, auto_id=False)
  2140. self.assertHTMLEqual(
  2141. f.as_table(),
  2142. '<tr><th>File1:</th><td>'
  2143. '<ul class="errorlist"><li>This field is required.</li></ul>'
  2144. '<input type="file" name="file1" required /></td></tr>'
  2145. )
  2146. f = FileForm(data={}, files={'file1': SimpleUploadedFile('name', b'')}, auto_id=False)
  2147. self.assertHTMLEqual(
  2148. f.as_table(),
  2149. '<tr><th>File1:</th><td>'
  2150. '<ul class="errorlist"><li>The submitted file is empty.</li></ul>'
  2151. '<input type="file" name="file1" required /></td></tr>'
  2152. )
  2153. f = FileForm(data={}, files={'file1': 'something that is not a file'}, auto_id=False)
  2154. self.assertHTMLEqual(
  2155. f.as_table(),
  2156. '<tr><th>File1:</th><td>'
  2157. '<ul class="errorlist"><li>No file was submitted. Check the '
  2158. 'encoding type on the form.</li></ul>'
  2159. '<input type="file" name="file1" required /></td></tr>'
  2160. )
  2161. f = FileForm(data={}, files={'file1': SimpleUploadedFile('name', b'some content')}, auto_id=False)
  2162. self.assertHTMLEqual(
  2163. f.as_table(),
  2164. '<tr><th>File1:</th><td><input type="file" name="file1" required /></td></tr>',
  2165. )
  2166. self.assertTrue(f.is_valid())
  2167. file1 = SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह'.encode('utf-8'))
  2168. f = FileForm(data={}, files={'file1': file1}, auto_id=False)
  2169. self.assertHTMLEqual(
  2170. f.as_table(),
  2171. '<tr><th>File1:</th><td><input type="file" name="file1" required /></td></tr>',
  2172. )
  2173. # A required file field with initial data should not contain the
  2174. # required HTML attribute. The file input is left blank by the user to
  2175. # keep the existing, initial value.
  2176. f = FileForm(initial={'file1': 'resume.txt'}, auto_id=False)
  2177. self.assertHTMLEqual(
  2178. f.as_table(),
  2179. '<tr><th>File1:</th><td><input type="file" name="file1" /></td></tr>',
  2180. )
  2181. def test_filefield_initial_callable(self):
  2182. class FileForm(forms.Form):
  2183. file1 = forms.FileField(initial=lambda: 'resume.txt')
  2184. f = FileForm({})
  2185. self.assertEqual(f.errors, {})
  2186. self.assertEqual(f.cleaned_data['file1'], 'resume.txt')
  2187. def test_basic_processing_in_view(self):
  2188. class UserRegistration(Form):
  2189. username = CharField(max_length=10)
  2190. password1 = CharField(widget=PasswordInput)
  2191. password2 = CharField(widget=PasswordInput)
  2192. def clean(self):
  2193. if (self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and
  2194. self.cleaned_data['password1'] != self.cleaned_data['password2']):
  2195. raise ValidationError('Please make sure your passwords match.')
  2196. return self.cleaned_data
  2197. def my_function(method, post_data):
  2198. if method == 'POST':
  2199. form = UserRegistration(post_data, auto_id=False)
  2200. else:
  2201. form = UserRegistration(auto_id=False)
  2202. if form.is_valid():
  2203. return 'VALID: %r' % sorted(form.cleaned_data.items())
  2204. t = Template(
  2205. '<form action="" method="post">\n'
  2206. '<table>\n{{ form }}\n</table>\n<input type="submit" required />\n</form>'
  2207. )
  2208. return t.render(Context({'form': form}))
  2209. # Case 1: GET (an empty form, with no errors).)
  2210. self.assertHTMLEqual(my_function('GET', {}), """<form action="" method="post">
  2211. <table>
  2212. <tr><th>Username:</th><td><input type="text" name="username" maxlength="10" required /></td></tr>
  2213. <tr><th>Password1:</th><td><input type="password" name="password1" required /></td></tr>
  2214. <tr><th>Password2:</th><td><input type="password" name="password2" required /></td></tr>
  2215. </table>
  2216. <input type="submit" required />
  2217. </form>""")
  2218. # Case 2: POST with erroneous data (a redisplayed form, with errors).)
  2219. self.assertHTMLEqual(
  2220. my_function('POST', {'username': 'this-is-a-long-username', 'password1': 'foo', 'password2': 'bar'}),
  2221. """<form action="" method="post">
  2222. <table>
  2223. <tr><td colspan="2"><ul class="errorlist nonfield"><li>Please make sure your passwords match.</li></ul></td></tr>
  2224. <tr><th>Username:</th><td><ul class="errorlist">
  2225. <li>Ensure this value has at most 10 characters (it has 23).</li></ul>
  2226. <input type="text" name="username" value="this-is-a-long-username" maxlength="10" required /></td></tr>
  2227. <tr><th>Password1:</th><td><input type="password" name="password1" required /></td></tr>
  2228. <tr><th>Password2:</th><td><input type="password" name="password2" required /></td></tr>
  2229. </table>
  2230. <input type="submit" required />
  2231. </form>"""
  2232. )
  2233. # Case 3: POST with valid data (the success message).)
  2234. self.assertEqual(
  2235. my_function('POST', {'username': 'adrian', 'password1': 'secret', 'password2': 'secret'}),
  2236. str_prefix(
  2237. "VALID: [('password1', %(_)s'secret'), ('password2', %(_)s'secret'), ('username', %(_)s'adrian')]"
  2238. )
  2239. )
  2240. def test_templates_with_forms(self):
  2241. class UserRegistration(Form):
  2242. username = CharField(max_length=10, help_text="Good luck picking a username that doesn't already exist.")
  2243. password1 = CharField(widget=PasswordInput)
  2244. password2 = CharField(widget=PasswordInput)
  2245. def clean(self):
  2246. if (self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and
  2247. self.cleaned_data['password1'] != self.cleaned_data['password2']):
  2248. raise ValidationError('Please make sure your passwords match.')
  2249. return self.cleaned_data
  2250. # You have full flexibility in displaying form fields in a template. Just pass a
  2251. # Form instance to the template, and use "dot" access to refer to individual
  2252. # fields. Note, however, that this flexibility comes with the responsibility of
  2253. # displaying all the errors, including any that might not be associated with a
  2254. # particular field.
  2255. t = Template('''<form action="">
  2256. {{ form.username.errors.as_ul }}<p><label>Your username: {{ form.username }}</label></p>
  2257. {{ form.password1.errors.as_ul }}<p><label>Password: {{ form.password1 }}</label></p>
  2258. {{ form.password2.errors.as_ul }}<p><label>Password (again): {{ form.password2 }}</label></p>
  2259. <input type="submit" required />
  2260. </form>''')
  2261. self.assertHTMLEqual(t.render(Context({'form': UserRegistration(auto_id=False)})), """<form action="">
  2262. <p><label>Your username: <input type="text" name="username" maxlength="10" required /></label></p>
  2263. <p><label>Password: <input type="password" name="password1" required /></label></p>
  2264. <p><label>Password (again): <input type="password" name="password2" required /></label></p>
  2265. <input type="submit" required />
  2266. </form>""")
  2267. self.assertHTMLEqual(
  2268. t.render(Context({'form': UserRegistration({'username': 'django'}, auto_id=False)})),
  2269. """<form action="">
  2270. <p><label>Your username: <input type="text" name="username" value="django" maxlength="10" required /></label></p>
  2271. <ul class="errorlist"><li>This field is required.</li></ul><p>
  2272. <label>Password: <input type="password" name="password1" required /></label></p>
  2273. <ul class="errorlist"><li>This field is required.</li></ul>
  2274. <p><label>Password (again): <input type="password" name="password2" required /></label></p>
  2275. <input type="submit" required />
  2276. </form>"""
  2277. )
  2278. # Use form.[field].label to output a field's label. You can specify the label for
  2279. # a field by using the 'label' argument to a Field class. If you don't specify
  2280. # 'label', Django will use the field name with underscores converted to spaces,
  2281. # and the initial letter capitalized.
  2282. t = Template('''<form action="">
  2283. <p><label>{{ form.username.label }}: {{ form.username }}</label></p>
  2284. <p><label>{{ form.password1.label }}: {{ form.password1 }}</label></p>
  2285. <p><label>{{ form.password2.label }}: {{ form.password2 }}</label></p>
  2286. <input type="submit" required />
  2287. </form>''')
  2288. self.assertHTMLEqual(t.render(Context({'form': UserRegistration(auto_id=False)})), """<form action="">
  2289. <p><label>Username: <input type="text" name="username" maxlength="10" required /></label></p>
  2290. <p><label>Password1: <input type="password" name="password1" required /></label></p>
  2291. <p><label>Password2: <input type="password" name="password2" required /></label></p>
  2292. <input type="submit" required />
  2293. </form>""")
  2294. # User form.[field].label_tag to output a field's label with a <label> tag
  2295. # wrapped around it, but *only* if the given field has an "id" attribute.
  2296. # Recall from above that passing the "auto_id" argument to a Form gives each
  2297. # field an "id" attribute.
  2298. t = Template('''<form action="">
  2299. <p>{{ form.username.label_tag }} {{ form.username }}</p>
  2300. <p>{{ form.password1.label_tag }} {{ form.password1 }}</p>
  2301. <p>{{ form.password2.label_tag }} {{ form.password2 }}</p>
  2302. <input type="submit" required />
  2303. </form>''')
  2304. self.assertHTMLEqual(t.render(Context({'form': UserRegistration(auto_id=False)})), """<form action="">
  2305. <p>Username: <input type="text" name="username" maxlength="10" required /></p>
  2306. <p>Password1: <input type="password" name="password1" required /></p>
  2307. <p>Password2: <input type="password" name="password2" required /></p>
  2308. <input type="submit" required />
  2309. </form>""")
  2310. self.assertHTMLEqual(t.render(Context({'form': UserRegistration(auto_id='id_%s')})), """<form action="">
  2311. <p><label for="id_username">Username:</label>
  2312. <input id="id_username" type="text" name="username" maxlength="10" required /></p>
  2313. <p><label for="id_password1">Password1:</label>
  2314. <input type="password" name="password1" id="id_password1" required /></p>
  2315. <p><label for="id_password2">Password2:</label>
  2316. <input type="password" name="password2" id="id_password2" required /></p>
  2317. <input type="submit" required />
  2318. </form>""")
  2319. # User form.[field].help_text to output a field's help text. If the given field
  2320. # does not have help text, nothing will be output.
  2321. t = Template('''<form action="">
  2322. <p>{{ form.username.label_tag }} {{ form.username }}<br />{{ form.username.help_text }}</p>
  2323. <p>{{ form.password1.label_tag }} {{ form.password1 }}</p>
  2324. <p>{{ form.password2.label_tag }} {{ form.password2 }}</p>
  2325. <input type="submit" required />
  2326. </form>''')
  2327. self.assertHTMLEqual(
  2328. t.render(Context({'form': UserRegistration(auto_id=False)})),
  2329. """<form action="">
  2330. <p>Username: <input type="text" name="username" maxlength="10" required /><br />
  2331. Good luck picking a username that doesn&#39;t already exist.</p>
  2332. <p>Password1: <input type="password" name="password1" required /></p>
  2333. <p>Password2: <input type="password" name="password2" required /></p>
  2334. <input type="submit" required />
  2335. </form>"""
  2336. )
  2337. self.assertEqual(
  2338. Template('{{ form.password1.help_text }}').render(Context({'form': UserRegistration(auto_id=False)})),
  2339. ''
  2340. )
  2341. # To display the errors that aren't associated with a particular field -- e.g.,
  2342. # the errors caused by Form.clean() -- use {{ form.non_field_errors }} in the
  2343. # template. If used on its own, it is displayed as a <ul> (or an empty string, if
  2344. # the list of errors is empty). You can also use it in {% if %} statements.
  2345. t = Template('''<form action="">
  2346. {{ form.username.errors.as_ul }}<p><label>Your username: {{ form.username }}</label></p>
  2347. {{ form.password1.errors.as_ul }}<p><label>Password: {{ form.password1 }}</label></p>
  2348. {{ form.password2.errors.as_ul }}<p><label>Password (again): {{ form.password2 }}</label></p>
  2349. <input type="submit" required />
  2350. </form>''')
  2351. self.assertHTMLEqual(
  2352. t.render(Context({
  2353. 'form': UserRegistration({'username': 'django', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)
  2354. })),
  2355. """<form action="">
  2356. <p><label>Your username: <input type="text" name="username" value="django" maxlength="10" required /></label></p>
  2357. <p><label>Password: <input type="password" name="password1" required /></label></p>
  2358. <p><label>Password (again): <input type="password" name="password2" required /></label></p>
  2359. <input type="submit" required />
  2360. </form>"""
  2361. )
  2362. t = Template('''<form action="">
  2363. {{ form.non_field_errors }}
  2364. {{ form.username.errors.as_ul }}<p><label>Your username: {{ form.username }}</label></p>
  2365. {{ form.password1.errors.as_ul }}<p><label>Password: {{ form.password1 }}</label></p>
  2366. {{ form.password2.errors.as_ul }}<p><label>Password (again): {{ form.password2 }}</label></p>
  2367. <input type="submit" required />
  2368. </form>''')
  2369. self.assertHTMLEqual(
  2370. t.render(Context({
  2371. 'form': UserRegistration({'username': 'django', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)
  2372. })),
  2373. """<form action="">
  2374. <ul class="errorlist nonfield"><li>Please make sure your passwords match.</li></ul>
  2375. <p><label>Your username: <input type="text" name="username" value="django" maxlength="10" required /></label></p>
  2376. <p><label>Password: <input type="password" name="password1" required /></label></p>
  2377. <p><label>Password (again): <input type="password" name="password2" required /></label></p>
  2378. <input type="submit" required />
  2379. </form>"""
  2380. )
  2381. def test_empty_permitted(self):
  2382. # Sometimes (pretty much in formsets) we want to allow a form to pass validation
  2383. # if it is completely empty. We can accomplish this by using the empty_permitted
  2384. # argument to a form constructor.
  2385. class SongForm(Form):
  2386. artist = CharField()
  2387. name = CharField()
  2388. # First let's show what happens id empty_permitted=False (the default):
  2389. data = {'artist': '', 'song': ''}
  2390. form = SongForm(data, empty_permitted=False)
  2391. self.assertFalse(form.is_valid())
  2392. self.assertEqual(form.errors, {'name': ['This field is required.'], 'artist': ['This field is required.']})
  2393. self.assertEqual(form.cleaned_data, {})
  2394. # Now let's show what happens when empty_permitted=True and the form is empty.
  2395. form = SongForm(data, empty_permitted=True)
  2396. self.assertTrue(form.is_valid())
  2397. self.assertEqual(form.errors, {})
  2398. self.assertEqual(form.cleaned_data, {})
  2399. # But if we fill in data for one of the fields, the form is no longer empty and
  2400. # the whole thing must pass validation.
  2401. data = {'artist': 'The Doors', 'song': ''}
  2402. form = SongForm(data, empty_permitted=False)
  2403. self.assertFalse(form.is_valid())
  2404. self.assertEqual(form.errors, {'name': ['This field is required.']})
  2405. self.assertEqual(form.cleaned_data, {'artist': 'The Doors'})
  2406. # If a field is not given in the data then None is returned for its data. Lets
  2407. # make sure that when checking for empty_permitted that None is treated
  2408. # accordingly.
  2409. data = {'artist': None, 'song': ''}
  2410. form = SongForm(data, empty_permitted=True)
  2411. self.assertTrue(form.is_valid())
  2412. # However, we *really* need to be sure we are checking for None as any data in
  2413. # initial that returns False on a boolean call needs to be treated literally.
  2414. class PriceForm(Form):
  2415. amount = FloatField()
  2416. qty = IntegerField()
  2417. data = {'amount': '0.0', 'qty': ''}
  2418. form = PriceForm(data, initial={'amount': 0.0}, empty_permitted=True)
  2419. self.assertTrue(form.is_valid())
  2420. def test_extracting_hidden_and_visible(self):
  2421. class SongForm(Form):
  2422. token = CharField(widget=HiddenInput)
  2423. artist = CharField()
  2424. name = CharField()
  2425. form = SongForm()
  2426. self.assertEqual([f.name for f in form.hidden_fields()], ['token'])
  2427. self.assertEqual([f.name for f in form.visible_fields()], ['artist', 'name'])
  2428. def test_hidden_initial_gets_id(self):
  2429. class MyForm(Form):
  2430. field1 = CharField(max_length=50, show_hidden_initial=True)
  2431. self.assertHTMLEqual(
  2432. MyForm().as_table(),
  2433. '<tr><th><label for="id_field1">Field1:</label></th>'
  2434. '<td><input id="id_field1" type="text" name="field1" maxlength="50" required />'
  2435. '<input type="hidden" name="initial-field1" id="initial-id_field1" /></td></tr>'
  2436. )
  2437. def test_error_html_required_html_classes(self):
  2438. class Person(Form):
  2439. name = CharField()
  2440. is_cool = NullBooleanField()
  2441. email = EmailField(required=False)
  2442. age = IntegerField()
  2443. p = Person({})
  2444. p.error_css_class = 'error'
  2445. p.required_css_class = 'required'
  2446. self.assertHTMLEqual(
  2447. p.as_ul(),
  2448. """<li class="required error"><ul class="errorlist"><li>This field is required.</li></ul>
  2449. <label class="required" for="id_name">Name:</label> <input type="text" name="name" id="id_name" required /></li>
  2450. <li class="required"><label class="required" for="id_is_cool">Is cool:</label>
  2451. <select name="is_cool" id="id_is_cool" required>
  2452. <option value="1" selected>Unknown</option>
  2453. <option value="2">Yes</option>
  2454. <option value="3">No</option>
  2455. </select></li>
  2456. <li><label for="id_email">Email:</label> <input type="email" name="email" id="id_email" /></li>
  2457. <li class="required error"><ul class="errorlist"><li>This field is required.</li></ul>
  2458. <label class="required" for="id_age">Age:</label> <input type="number" name="age" id="id_age" required /></li>"""
  2459. )
  2460. self.assertHTMLEqual(
  2461. p.as_p(),
  2462. """<ul class="errorlist"><li>This field is required.</li></ul>
  2463. <p class="required error"><label class="required" for="id_name">Name:</label>
  2464. <input type="text" name="name" id="id_name" required /></p>
  2465. <p class="required"><label class="required" for="id_is_cool">Is cool:</label>
  2466. <select name="is_cool" id="id_is_cool" required>
  2467. <option value="1" selected>Unknown</option>
  2468. <option value="2">Yes</option>
  2469. <option value="3">No</option>
  2470. </select></p>
  2471. <p><label for="id_email">Email:</label> <input type="email" name="email" id="id_email" /></p>
  2472. <ul class="errorlist"><li>This field is required.</li></ul>
  2473. <p class="required error"><label class="required" for="id_age">Age:</label>
  2474. <input type="number" name="age" id="id_age" required /></p>"""
  2475. )
  2476. self.assertHTMLEqual(
  2477. p.as_table(),
  2478. """<tr class="required error">
  2479. <th><label class="required" for="id_name">Name:</label></th>
  2480. <td><ul class="errorlist"><li>This field is required.</li></ul>
  2481. <input type="text" name="name" id="id_name" required /></td></tr>
  2482. <tr class="required"><th><label class="required" for="id_is_cool">Is cool:</label></th>
  2483. <td><select name="is_cool" id="id_is_cool" required>
  2484. <option value="1" selected>Unknown</option>
  2485. <option value="2">Yes</option>
  2486. <option value="3">No</option>
  2487. </select></td></tr>
  2488. <tr><th><label for="id_email">Email:</label></th><td>
  2489. <input type="email" name="email" id="id_email" /></td></tr>
  2490. <tr class="required error"><th><label class="required" for="id_age">Age:</label></th>
  2491. <td><ul class="errorlist"><li>This field is required.</li></ul>
  2492. <input type="number" name="age" id="id_age" required /></td></tr>"""
  2493. )
  2494. def test_label_has_required_css_class(self):
  2495. """
  2496. #17922 - required_css_class is added to the label_tag() of required fields.
  2497. """
  2498. class SomeForm(Form):
  2499. required_css_class = 'required'
  2500. field = CharField(max_length=10)
  2501. field2 = IntegerField(required=False)
  2502. f = SomeForm({'field': 'test'})
  2503. self.assertHTMLEqual(f['field'].label_tag(), '<label for="id_field" class="required">Field:</label>')
  2504. self.assertHTMLEqual(
  2505. f['field'].label_tag(attrs={'class': 'foo'}),
  2506. '<label for="id_field" class="foo required">Field:</label>'
  2507. )
  2508. self.assertHTMLEqual(f['field2'].label_tag(), '<label for="id_field2">Field2:</label>')
  2509. def test_label_split_datetime_not_displayed(self):
  2510. class EventForm(Form):
  2511. happened_at = SplitDateTimeField(widget=SplitHiddenDateTimeWidget)
  2512. form = EventForm()
  2513. self.assertHTMLEqual(
  2514. form.as_ul(),
  2515. '<input type="hidden" name="happened_at_0" id="id_happened_at_0" />'
  2516. '<input type="hidden" name="happened_at_1" id="id_happened_at_1" />'
  2517. )
  2518. def test_multivalue_field_validation(self):
  2519. def bad_names(value):
  2520. if value == 'bad value':
  2521. raise ValidationError('bad value not allowed')
  2522. class NameField(MultiValueField):
  2523. def __init__(self, fields=(), *args, **kwargs):
  2524. fields = (CharField(label='First name', max_length=10),
  2525. CharField(label='Last name', max_length=10))
  2526. super(NameField, self).__init__(fields=fields, *args, **kwargs)
  2527. def compress(self, data_list):
  2528. return ' '.join(data_list)
  2529. class NameForm(Form):
  2530. name = NameField(validators=[bad_names])
  2531. form = NameForm(data={'name': ['bad', 'value']})
  2532. form.full_clean()
  2533. self.assertFalse(form.is_valid())
  2534. self.assertEqual(form.errors, {'name': ['bad value not allowed']})
  2535. form = NameForm(data={'name': ['should be overly', 'long for the field names']})
  2536. self.assertFalse(form.is_valid())
  2537. self.assertEqual(form.errors, {'name': ['Ensure this value has at most 10 characters (it has 16).',
  2538. 'Ensure this value has at most 10 characters (it has 24).']})
  2539. form = NameForm(data={'name': ['fname', 'lname']})
  2540. self.assertTrue(form.is_valid())
  2541. self.assertEqual(form.cleaned_data, {'name': 'fname lname'})
  2542. def test_multivalue_deep_copy(self):
  2543. """
  2544. #19298 -- MultiValueField needs to override the default as it needs
  2545. to deep-copy subfields:
  2546. """
  2547. class ChoicesField(MultiValueField):
  2548. def __init__(self, fields=(), *args, **kwargs):
  2549. fields = (
  2550. ChoiceField(label='Rank', choices=((1, 1), (2, 2))),
  2551. CharField(label='Name', max_length=10),
  2552. )
  2553. super(ChoicesField, self).__init__(fields=fields, *args, **kwargs)
  2554. field = ChoicesField()
  2555. field2 = copy.deepcopy(field)
  2556. self.assertIsInstance(field2, ChoicesField)
  2557. self.assertIsNot(field2.fields, field.fields)
  2558. self.assertIsNot(field2.fields[0].choices, field.fields[0].choices)
  2559. def test_multivalue_initial_data(self):
  2560. """
  2561. #23674 -- invalid initial data should not break form.changed_data()
  2562. """
  2563. class DateAgeField(MultiValueField):
  2564. def __init__(self, fields=(), *args, **kwargs):
  2565. fields = (DateField(label="Date"), IntegerField(label="Age"))
  2566. super(DateAgeField, self).__init__(fields=fields, *args, **kwargs)
  2567. class DateAgeForm(Form):
  2568. date_age = DateAgeField()
  2569. data = {"date_age": ["1998-12-06", 16]}
  2570. form = DateAgeForm(data, initial={"date_age": ["200-10-10", 14]})
  2571. self.assertTrue(form.has_changed())
  2572. def test_multivalue_optional_subfields(self):
  2573. class PhoneField(MultiValueField):
  2574. def __init__(self, *args, **kwargs):
  2575. fields = (
  2576. CharField(label='Country Code', validators=[
  2577. RegexValidator(r'^\+[0-9]{1,2}$', message='Enter a valid country code.')]),
  2578. CharField(label='Phone Number'),
  2579. CharField(label='Extension', error_messages={'incomplete': 'Enter an extension.'}),
  2580. CharField(label='Label', required=False, help_text='E.g. home, work.'),
  2581. )
  2582. super(PhoneField, self).__init__(fields, *args, **kwargs)
  2583. def compress(self, data_list):
  2584. if data_list:
  2585. return '%s.%s ext. %s (label: %s)' % tuple(data_list)
  2586. return None
  2587. # An empty value for any field will raise a `required` error on a
  2588. # required `MultiValueField`.
  2589. f = PhoneField()
  2590. with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
  2591. f.clean('')
  2592. with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
  2593. f.clean(None)
  2594. with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
  2595. f.clean([])
  2596. with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
  2597. f.clean(['+61'])
  2598. with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
  2599. f.clean(['+61', '287654321', '123'])
  2600. self.assertEqual('+61.287654321 ext. 123 (label: Home)', f.clean(['+61', '287654321', '123', 'Home']))
  2601. with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"):
  2602. f.clean(['61', '287654321', '123', 'Home'])
  2603. # Empty values for fields will NOT raise a `required` error on an
  2604. # optional `MultiValueField`
  2605. f = PhoneField(required=False)
  2606. self.assertIsNone(f.clean(''))
  2607. self.assertIsNone(f.clean(None))
  2608. self.assertIsNone(f.clean([]))
  2609. self.assertEqual('+61. ext. (label: )', f.clean(['+61']))
  2610. self.assertEqual('+61.287654321 ext. 123 (label: )', f.clean(['+61', '287654321', '123']))
  2611. self.assertEqual('+61.287654321 ext. 123 (label: Home)', f.clean(['+61', '287654321', '123', 'Home']))
  2612. with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"):
  2613. f.clean(['61', '287654321', '123', 'Home'])
  2614. # For a required `MultiValueField` with `require_all_fields=False`, a
  2615. # `required` error will only be raised if all fields are empty. Fields
  2616. # can individually be required or optional. An empty value for any
  2617. # required field will raise an `incomplete` error.
  2618. f = PhoneField(require_all_fields=False)
  2619. with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
  2620. f.clean('')
  2621. with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
  2622. f.clean(None)
  2623. with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
  2624. f.clean([])
  2625. with self.assertRaisesMessage(ValidationError, "'Enter a complete value.'"):
  2626. f.clean(['+61'])
  2627. self.assertEqual('+61.287654321 ext. 123 (label: )', f.clean(['+61', '287654321', '123']))
  2628. self.assertRaisesRegex(
  2629. ValidationError,
  2630. r"'Enter a complete value\.', u?'Enter an extension\.'", f.clean, ['', '', '', 'Home']
  2631. )
  2632. with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"):
  2633. f.clean(['61', '287654321', '123', 'Home'])
  2634. # For an optional `MultiValueField` with `require_all_fields=False`, we
  2635. # don't get any `required` error but we still get `incomplete` errors.
  2636. f = PhoneField(required=False, require_all_fields=False)
  2637. self.assertIsNone(f.clean(''))
  2638. self.assertIsNone(f.clean(None))
  2639. self.assertIsNone(f.clean([]))
  2640. with self.assertRaisesMessage(ValidationError, "'Enter a complete value.'"):
  2641. f.clean(['+61'])
  2642. self.assertEqual('+61.287654321 ext. 123 (label: )', f.clean(['+61', '287654321', '123']))
  2643. with self.assertRaisesRegex(ValidationError, r"'Enter a complete value\.', u?'Enter an extension\.'"):
  2644. f.clean(['', '', '', 'Home'])
  2645. with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"):
  2646. f.clean(['61', '287654321', '123', 'Home'])
  2647. def test_custom_empty_values(self):
  2648. """
  2649. Form fields can customize what is considered as an empty value
  2650. for themselves (#19997).
  2651. """
  2652. class CustomJSONField(CharField):
  2653. empty_values = [None, '']
  2654. def to_python(self, value):
  2655. # Fake json.loads
  2656. if value == '{}':
  2657. return {}
  2658. return super(CustomJSONField, self).to_python(value)
  2659. class JSONForm(forms.Form):
  2660. json = CustomJSONField()
  2661. form = JSONForm(data={'json': '{}'})
  2662. form.full_clean()
  2663. self.assertEqual(form.cleaned_data, {'json': {}})
  2664. def test_boundfield_label_tag(self):
  2665. class SomeForm(Form):
  2666. field = CharField()
  2667. boundfield = SomeForm()['field']
  2668. testcases = [ # (args, kwargs, expected)
  2669. # without anything: just print the <label>
  2670. ((), {}, '<label for="id_field">Field:</label>'),
  2671. # passing just one argument: overrides the field's label
  2672. (('custom',), {}, '<label for="id_field">custom:</label>'),
  2673. # the overridden label is escaped
  2674. (('custom&',), {}, '<label for="id_field">custom&amp;:</label>'),
  2675. ((mark_safe('custom&'),), {}, '<label for="id_field">custom&:</label>'),
  2676. # Passing attrs to add extra attributes on the <label>
  2677. ((), {'attrs': {'class': 'pretty'}}, '<label for="id_field" class="pretty">Field:</label>')
  2678. ]
  2679. for args, kwargs, expected in testcases:
  2680. self.assertHTMLEqual(boundfield.label_tag(*args, **kwargs), expected)
  2681. def test_boundfield_label_tag_no_id(self):
  2682. """
  2683. If a widget has no id, label_tag just returns the text with no
  2684. surrounding <label>.
  2685. """
  2686. class SomeForm(Form):
  2687. field = CharField()
  2688. boundfield = SomeForm(auto_id='')['field']
  2689. self.assertHTMLEqual(boundfield.label_tag(), 'Field:')
  2690. self.assertHTMLEqual(boundfield.label_tag('Custom&'), 'Custom&amp;:')
  2691. def test_boundfield_label_tag_custom_widget_id_for_label(self):
  2692. class CustomIdForLabelTextInput(TextInput):
  2693. def id_for_label(self, id):
  2694. return 'custom_' + id
  2695. class EmptyIdForLabelTextInput(TextInput):
  2696. def id_for_label(self, id):
  2697. return None
  2698. class SomeForm(Form):
  2699. custom = CharField(widget=CustomIdForLabelTextInput)
  2700. empty = CharField(widget=EmptyIdForLabelTextInput)
  2701. form = SomeForm()
  2702. self.assertHTMLEqual(form['custom'].label_tag(), '<label for="custom_id_custom">Custom:</label>')
  2703. self.assertHTMLEqual(form['empty'].label_tag(), '<label>Empty:</label>')
  2704. def test_boundfield_empty_label(self):
  2705. class SomeForm(Form):
  2706. field = CharField(label='')
  2707. boundfield = SomeForm()['field']
  2708. self.assertHTMLEqual(boundfield.label_tag(), '<label for="id_field"></label>')
  2709. def test_boundfield_id_for_label(self):
  2710. class SomeForm(Form):
  2711. field = CharField(label='')
  2712. self.assertEqual(SomeForm()['field'].id_for_label, 'id_field')
  2713. def test_boundfield_id_for_label_override_by_attrs(self):
  2714. """
  2715. If an id is provided in `Widget.attrs`, it overrides the generated ID,
  2716. unless it is `None`.
  2717. """
  2718. class SomeForm(Form):
  2719. field = CharField(widget=TextInput(attrs={'id': 'myCustomID'}))
  2720. field_none = CharField(widget=TextInput(attrs={'id': None}))
  2721. form = SomeForm()
  2722. self.assertEqual(form['field'].id_for_label, 'myCustomID')
  2723. self.assertEqual(form['field_none'].id_for_label, 'id_field_none')
  2724. def test_label_tag_override(self):
  2725. """
  2726. BoundField label_suffix (if provided) overrides Form label_suffix
  2727. """
  2728. class SomeForm(Form):
  2729. field = CharField()
  2730. boundfield = SomeForm(label_suffix='!')['field']
  2731. self.assertHTMLEqual(boundfield.label_tag(label_suffix='$'), '<label for="id_field">Field$</label>')
  2732. def test_field_name(self):
  2733. """#5749 - `field_name` may be used as a key in _html_output()."""
  2734. class SomeForm(Form):
  2735. some_field = CharField()
  2736. def as_p(self):
  2737. return self._html_output(
  2738. normal_row='<p id="p_%(field_name)s"></p>',
  2739. error_row='%s',
  2740. row_ender='</p>',
  2741. help_text_html=' %s',
  2742. errors_on_separate_row=True,
  2743. )
  2744. form = SomeForm()
  2745. self.assertHTMLEqual(form.as_p(), '<p id="p_some_field"></p>')
  2746. def test_field_without_css_classes(self):
  2747. """
  2748. `css_classes` may be used as a key in _html_output() (empty classes).
  2749. """
  2750. class SomeForm(Form):
  2751. some_field = CharField()
  2752. def as_p(self):
  2753. return self._html_output(
  2754. normal_row='<p class="%(css_classes)s"></p>',
  2755. error_row='%s',
  2756. row_ender='</p>',
  2757. help_text_html=' %s',
  2758. errors_on_separate_row=True,
  2759. )
  2760. form = SomeForm()
  2761. self.assertHTMLEqual(form.as_p(), '<p class=""></p>')
  2762. def test_field_with_css_class(self):
  2763. """
  2764. `css_classes` may be used as a key in _html_output() (class comes
  2765. from required_css_class in this case).
  2766. """
  2767. class SomeForm(Form):
  2768. some_field = CharField()
  2769. required_css_class = 'foo'
  2770. def as_p(self):
  2771. return self._html_output(
  2772. normal_row='<p class="%(css_classes)s"></p>',
  2773. error_row='%s',
  2774. row_ender='</p>',
  2775. help_text_html=' %s',
  2776. errors_on_separate_row=True,
  2777. )
  2778. form = SomeForm()
  2779. self.assertHTMLEqual(form.as_p(), '<p class="foo"></p>')
  2780. def test_field_name_with_hidden_input(self):
  2781. """
  2782. BaseForm._html_output() should merge all the hidden input fields and
  2783. put them in the last row.
  2784. """
  2785. class SomeForm(Form):
  2786. hidden1 = CharField(widget=HiddenInput)
  2787. custom = CharField()
  2788. hidden2 = CharField(widget=HiddenInput)
  2789. def as_p(self):
  2790. return self._html_output(
  2791. normal_row='<p%(html_class_attr)s>%(field)s %(field_name)s</p>',
  2792. error_row='%s',
  2793. row_ender='</p>',
  2794. help_text_html=' %s',
  2795. errors_on_separate_row=True,
  2796. )
  2797. form = SomeForm()
  2798. self.assertHTMLEqual(
  2799. form.as_p(),
  2800. '<p><input id="id_custom" name="custom" type="text" required /> custom'
  2801. '<input id="id_hidden1" name="hidden1" type="hidden" />'
  2802. '<input id="id_hidden2" name="hidden2" type="hidden" /></p>'
  2803. )
  2804. def test_field_name_with_hidden_input_and_non_matching_row_ender(self):
  2805. """
  2806. BaseForm._html_output() should merge all the hidden input fields and
  2807. put them in the last row ended with the specific row ender.
  2808. """
  2809. class SomeForm(Form):
  2810. hidden1 = CharField(widget=HiddenInput)
  2811. custom = CharField()
  2812. hidden2 = CharField(widget=HiddenInput)
  2813. def as_p(self):
  2814. return self._html_output(
  2815. normal_row='<p%(html_class_attr)s>%(field)s %(field_name)s</p>',
  2816. error_row='%s',
  2817. row_ender='<hr /><hr />',
  2818. help_text_html=' %s',
  2819. errors_on_separate_row=True
  2820. )
  2821. form = SomeForm()
  2822. self.assertHTMLEqual(
  2823. form.as_p(),
  2824. '<p><input id="id_custom" name="custom" type="text" required /> custom</p>\n'
  2825. '<input id="id_hidden1" name="hidden1" type="hidden" />'
  2826. '<input id="id_hidden2" name="hidden2" type="hidden" /><hr /><hr />'
  2827. )
  2828. def test_error_dict(self):
  2829. class MyForm(Form):
  2830. foo = CharField()
  2831. bar = CharField()
  2832. def clean(self):
  2833. raise ValidationError('Non-field error.', code='secret', params={'a': 1, 'b': 2})
  2834. form = MyForm({})
  2835. self.assertIs(form.is_valid(), False)
  2836. errors = form.errors.as_text()
  2837. control = [
  2838. '* foo\n * This field is required.',
  2839. '* bar\n * This field is required.',
  2840. '* __all__\n * Non-field error.',
  2841. ]
  2842. for error in control:
  2843. self.assertIn(error, errors)
  2844. errors = form.errors.as_ul()
  2845. control = [
  2846. '<li>foo<ul class="errorlist"><li>This field is required.</li></ul></li>',
  2847. '<li>bar<ul class="errorlist"><li>This field is required.</li></ul></li>',
  2848. '<li>__all__<ul class="errorlist nonfield"><li>Non-field error.</li></ul></li>',
  2849. ]
  2850. for error in control:
  2851. self.assertInHTML(error, errors)
  2852. errors = json.loads(form.errors.as_json())
  2853. control = {
  2854. 'foo': [{'code': 'required', 'message': 'This field is required.'}],
  2855. 'bar': [{'code': 'required', 'message': 'This field is required.'}],
  2856. '__all__': [{'code': 'secret', 'message': 'Non-field error.'}]
  2857. }
  2858. self.assertEqual(errors, control)
  2859. def test_error_dict_as_json_escape_html(self):
  2860. """#21962 - adding html escape flag to ErrorDict"""
  2861. class MyForm(Form):
  2862. foo = CharField()
  2863. bar = CharField()
  2864. def clean(self):
  2865. raise ValidationError('<p>Non-field error.</p>',
  2866. code='secret',
  2867. params={'a': 1, 'b': 2})
  2868. control = {
  2869. 'foo': [{'code': 'required', 'message': 'This field is required.'}],
  2870. 'bar': [{'code': 'required', 'message': 'This field is required.'}],
  2871. '__all__': [{'code': 'secret', 'message': '<p>Non-field error.</p>'}]
  2872. }
  2873. form = MyForm({})
  2874. self.assertFalse(form.is_valid())
  2875. errors = json.loads(form.errors.as_json())
  2876. self.assertEqual(errors, control)
  2877. errors = json.loads(form.errors.as_json(escape_html=True))
  2878. control['__all__'][0]['message'] = '&lt;p&gt;Non-field error.&lt;/p&gt;'
  2879. self.assertEqual(errors, control)
  2880. def test_error_list(self):
  2881. e = ErrorList()
  2882. e.append('Foo')
  2883. e.append(ValidationError('Foo%(bar)s', code='foobar', params={'bar': 'bar'}))
  2884. self.assertIsInstance(e, list)
  2885. self.assertIn('Foo', e)
  2886. self.assertIn('Foo', forms.ValidationError(e))
  2887. self.assertEqual(
  2888. e.as_text(),
  2889. '* Foo\n* Foobar'
  2890. )
  2891. self.assertEqual(
  2892. e.as_ul(),
  2893. '<ul class="errorlist"><li>Foo</li><li>Foobar</li></ul>'
  2894. )
  2895. self.assertEqual(
  2896. json.loads(e.as_json()),
  2897. [{"message": "Foo", "code": ""}, {"message": "Foobar", "code": "foobar"}]
  2898. )
  2899. def test_error_list_class_not_specified(self):
  2900. e = ErrorList()
  2901. e.append('Foo')
  2902. e.append(ValidationError('Foo%(bar)s', code='foobar', params={'bar': 'bar'}))
  2903. self.assertEqual(
  2904. e.as_ul(),
  2905. '<ul class="errorlist"><li>Foo</li><li>Foobar</li></ul>'
  2906. )
  2907. def test_error_list_class_has_one_class_specified(self):
  2908. e = ErrorList(error_class='foobar-error-class')
  2909. e.append('Foo')
  2910. e.append(ValidationError('Foo%(bar)s', code='foobar', params={'bar': 'bar'}))
  2911. self.assertEqual(
  2912. e.as_ul(),
  2913. '<ul class="errorlist foobar-error-class"><li>Foo</li><li>Foobar</li></ul>'
  2914. )
  2915. def test_error_list_with_hidden_field_errors_has_correct_class(self):
  2916. class Person(Form):
  2917. first_name = CharField()
  2918. last_name = CharField(widget=HiddenInput)
  2919. p = Person({'first_name': 'John'})
  2920. self.assertHTMLEqual(
  2921. p.as_ul(),
  2922. """<li><ul class="errorlist nonfield">
  2923. <li>(Hidden field last_name) This field is required.</li></ul></li><li>
  2924. <label for="id_first_name">First name:</label>
  2925. <input id="id_first_name" name="first_name" type="text" value="John" required />
  2926. <input id="id_last_name" name="last_name" type="hidden" /></li>"""
  2927. )
  2928. self.assertHTMLEqual(
  2929. p.as_p(),
  2930. """<ul class="errorlist nonfield"><li>(Hidden field last_name) This field is required.</li></ul>
  2931. <p><label for="id_first_name">First name:</label>
  2932. <input id="id_first_name" name="first_name" type="text" value="John" required />
  2933. <input id="id_last_name" name="last_name" type="hidden" /></p>"""
  2934. )
  2935. self.assertHTMLEqual(
  2936. p.as_table(),
  2937. """<tr><td colspan="2"><ul class="errorlist nonfield">
  2938. <li>(Hidden field last_name) This field is required.</li></ul></td></tr>
  2939. <tr><th><label for="id_first_name">First name:</label></th><td>
  2940. <input id="id_first_name" name="first_name" type="text" value="John" required />
  2941. <input id="id_last_name" name="last_name" type="hidden" /></td></tr>"""
  2942. )
  2943. def test_error_list_with_non_field_errors_has_correct_class(self):
  2944. class Person(Form):
  2945. first_name = CharField()
  2946. last_name = CharField()
  2947. def clean(self):
  2948. raise ValidationError('Generic validation error')
  2949. p = Person({'first_name': 'John', 'last_name': 'Lennon'})
  2950. self.assertHTMLEqual(
  2951. str(p.non_field_errors()),
  2952. '<ul class="errorlist nonfield"><li>Generic validation error</li></ul>'
  2953. )
  2954. self.assertHTMLEqual(
  2955. p.as_ul(),
  2956. """<li>
  2957. <ul class="errorlist nonfield"><li>Generic validation error</li></ul></li>
  2958. <li><label for="id_first_name">First name:</label>
  2959. <input id="id_first_name" name="first_name" type="text" value="John" required /></li>
  2960. <li><label for="id_last_name">Last name:</label>
  2961. <input id="id_last_name" name="last_name" type="text" value="Lennon" required /></li>"""
  2962. )
  2963. self.assertHTMLEqual(
  2964. p.non_field_errors().as_text(),
  2965. '* Generic validation error'
  2966. )
  2967. self.assertHTMLEqual(
  2968. p.as_p(),
  2969. """<ul class="errorlist nonfield"><li>Generic validation error</li></ul>
  2970. <p><label for="id_first_name">First name:</label>
  2971. <input id="id_first_name" name="first_name" type="text" value="John" required /></p>
  2972. <p><label for="id_last_name">Last name:</label>
  2973. <input id="id_last_name" name="last_name" type="text" value="Lennon" required /></p>"""
  2974. )
  2975. self.assertHTMLEqual(
  2976. p.as_table(),
  2977. """<tr><td colspan="2"><ul class="errorlist nonfield"><li>Generic validation error</li></ul></td></tr>
  2978. <tr><th><label for="id_first_name">First name:</label></th><td>
  2979. <input id="id_first_name" name="first_name" type="text" value="John" required /></td></tr>
  2980. <tr><th><label for="id_last_name">Last name:</label></th><td>
  2981. <input id="id_last_name" name="last_name" type="text" value="Lennon" required /></td></tr>"""
  2982. )
  2983. def test_errorlist_override(self):
  2984. @python_2_unicode_compatible
  2985. class DivErrorList(ErrorList):
  2986. def __str__(self):
  2987. return self.as_divs()
  2988. def as_divs(self):
  2989. if not self:
  2990. return ''
  2991. return '<div class="errorlist">%s</div>' % ''.join(
  2992. '<div class="error">%s</div>' % force_text(e) for e in self)
  2993. class CommentForm(Form):
  2994. name = CharField(max_length=50, required=False)
  2995. email = EmailField()
  2996. comment = CharField()
  2997. data = dict(email='invalid')
  2998. f = CommentForm(data, auto_id=False, error_class=DivErrorList)
  2999. self.assertHTMLEqual(f.as_p(), """<p>Name: <input type="text" name="name" maxlength="50" /></p>
  3000. <div class="errorlist"><div class="error">Enter a valid email address.</div></div>
  3001. <p>Email: <input type="email" name="email" value="invalid" required /></p>
  3002. <div class="errorlist"><div class="error">This field is required.</div></div>
  3003. <p>Comment: <input type="text" name="comment" required /></p>""")
  3004. def test_baseform_repr(self):
  3005. """
  3006. BaseForm.__repr__() should contain some basic information about the
  3007. form.
  3008. """
  3009. p = Person()
  3010. self.assertEqual(repr(p), "<Person bound=False, valid=Unknown, fields=(first_name;last_name;birthday)>")
  3011. p = Person({'first_name': 'John', 'last_name': 'Lennon', 'birthday': '1940-10-9'})
  3012. self.assertEqual(repr(p), "<Person bound=True, valid=Unknown, fields=(first_name;last_name;birthday)>")
  3013. p.is_valid()
  3014. self.assertEqual(repr(p), "<Person bound=True, valid=True, fields=(first_name;last_name;birthday)>")
  3015. p = Person({'first_name': 'John', 'last_name': 'Lennon', 'birthday': 'fakedate'})
  3016. p.is_valid()
  3017. self.assertEqual(repr(p), "<Person bound=True, valid=False, fields=(first_name;last_name;birthday)>")
  3018. def test_baseform_repr_dont_trigger_validation(self):
  3019. """
  3020. BaseForm.__repr__() shouldn't trigger the form validation.
  3021. """
  3022. p = Person({'first_name': 'John', 'last_name': 'Lennon', 'birthday': 'fakedate'})
  3023. repr(p)
  3024. with self.assertRaises(AttributeError):
  3025. p.cleaned_data
  3026. self.assertFalse(p.is_valid())
  3027. self.assertEqual(p.cleaned_data, {'first_name': 'John', 'last_name': 'Lennon'})
  3028. def test_accessing_clean(self):
  3029. class UserForm(Form):
  3030. username = CharField(max_length=10)
  3031. password = CharField(widget=PasswordInput)
  3032. def clean(self):
  3033. data = self.cleaned_data
  3034. if not self.errors:
  3035. data['username'] = data['username'].lower()
  3036. return data
  3037. f = UserForm({'username': 'SirRobin', 'password': 'blue'})
  3038. self.assertTrue(f.is_valid())
  3039. self.assertEqual(f.cleaned_data['username'], 'sirrobin')
  3040. def test_changing_cleaned_data_nothing_returned(self):
  3041. class UserForm(Form):
  3042. username = CharField(max_length=10)
  3043. password = CharField(widget=PasswordInput)
  3044. def clean(self):
  3045. self.cleaned_data['username'] = self.cleaned_data['username'].lower()
  3046. # don't return anything
  3047. f = UserForm({'username': 'SirRobin', 'password': 'blue'})
  3048. self.assertTrue(f.is_valid())
  3049. self.assertEqual(f.cleaned_data['username'], 'sirrobin')
  3050. def test_changing_cleaned_data_in_clean(self):
  3051. class UserForm(Form):
  3052. username = CharField(max_length=10)
  3053. password = CharField(widget=PasswordInput)
  3054. def clean(self):
  3055. data = self.cleaned_data
  3056. # Return a different dict. We have not changed self.cleaned_data.
  3057. return {
  3058. 'username': data['username'].lower(),
  3059. 'password': 'this_is_not_a_secret',
  3060. }
  3061. f = UserForm({'username': 'SirRobin', 'password': 'blue'})
  3062. self.assertTrue(f.is_valid())
  3063. self.assertEqual(f.cleaned_data['username'], 'sirrobin')
  3064. def test_multipart_encoded_form(self):
  3065. class FormWithoutFile(Form):
  3066. username = CharField()
  3067. class FormWithFile(Form):
  3068. username = CharField()
  3069. file = FileField()
  3070. class FormWithImage(Form):
  3071. image = ImageField()
  3072. self.assertFalse(FormWithoutFile().is_multipart())
  3073. self.assertTrue(FormWithFile().is_multipart())
  3074. self.assertTrue(FormWithImage().is_multipart())
  3075. def test_html_safe(self):
  3076. class SimpleForm(Form):
  3077. username = CharField()
  3078. form = SimpleForm()
  3079. self.assertTrue(hasattr(SimpleForm, '__html__'))
  3080. self.assertEqual(force_text(form), form.__html__())
  3081. self.assertTrue(hasattr(form['username'], '__html__'))
  3082. self.assertEqual(force_text(form['username']), form['username'].__html__())
  3083. def test_use_required_attribute_true(self):
  3084. class MyForm(Form):
  3085. use_required_attribute = True
  3086. f1 = CharField(max_length=30)
  3087. f2 = CharField(max_length=30, required=False)
  3088. f3 = CharField(widget=Textarea)
  3089. f4 = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')])
  3090. form = MyForm()
  3091. self.assertHTMLEqual(
  3092. form.as_p(),
  3093. '<p><label for="id_f1">F1:</label> <input id="id_f1" maxlength="30" name="f1" type="text" required /></p>'
  3094. '<p><label for="id_f2">F2:</label> <input id="id_f2" maxlength="30" name="f2" type="text" /></p>'
  3095. '<p><label for="id_f3">F3:</label> <textarea cols="40" id="id_f3" name="f3" rows="10" required>'
  3096. '</textarea></p>'
  3097. '<p><label for="id_f4">F4:</label> <select id="id_f4" name="f4" required>'
  3098. '<option value="P">Python</option>'
  3099. '<option value="J">Java</option>'
  3100. '</select></p>',
  3101. )
  3102. self.assertHTMLEqual(
  3103. form.as_ul(),
  3104. '<li><label for="id_f1">F1:</label> '
  3105. '<input id="id_f1" maxlength="30" name="f1" type="text" required /></li>'
  3106. '<li><label for="id_f2">F2:</label> <input id="id_f2" maxlength="30" name="f2" type="text" /></li>'
  3107. '<li><label for="id_f3">F3:</label> <textarea cols="40" id="id_f3" name="f3" rows="10" required>'
  3108. '</textarea></li>'
  3109. '<li><label for="id_f4">F4:</label> <select id="id_f4" name="f4" required>'
  3110. '<option value="P">Python</option>'
  3111. '<option value="J">Java</option>'
  3112. '</select></li>',
  3113. )
  3114. self.assertHTMLEqual(
  3115. form.as_table(),
  3116. '<tr><th><label for="id_f1">F1:</label></th>'
  3117. '<td><input id="id_f1" maxlength="30" name="f1" type="text" required /></td></tr>'
  3118. '<tr><th><label for="id_f2">F2:</label></th>'
  3119. '<td><input id="id_f2" maxlength="30" name="f2" type="text" /></td></tr>'
  3120. '<tr><th><label for="id_f3">F3:</label></th>'
  3121. '<td><textarea cols="40" id="id_f3" name="f3" rows="10" required>'
  3122. '</textarea></td></tr>'
  3123. '<tr><th><label for="id_f4">F4:</label></th><td><select id="id_f4" name="f4" required>'
  3124. '<option value="P">Python</option>'
  3125. '<option value="J">Java</option>'
  3126. '</select></td></tr>',
  3127. )
  3128. def test_use_required_attribute_false(self):
  3129. class MyForm(Form):
  3130. use_required_attribute = False
  3131. f1 = CharField(max_length=30)
  3132. f2 = CharField(max_length=30, required=False)
  3133. f3 = CharField(widget=Textarea)
  3134. f4 = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')])
  3135. form = MyForm()
  3136. self.assertHTMLEqual(
  3137. form.as_p(),
  3138. '<p><label for="id_f1">F1:</label> <input id="id_f1" maxlength="30" name="f1" type="text" /></p>'
  3139. '<p><label for="id_f2">F2:</label> <input id="id_f2" maxlength="30" name="f2" type="text" /></p>'
  3140. '<p><label for="id_f3">F3:</label> <textarea cols="40" id="id_f3" name="f3" rows="10">'
  3141. '</textarea></p>'
  3142. '<p><label for="id_f4">F4:</label> <select id="id_f4" name="f4">'
  3143. '<option value="P">Python</option>'
  3144. '<option value="J">Java</option>'
  3145. '</select></p>',
  3146. )
  3147. self.assertHTMLEqual(
  3148. form.as_ul(),
  3149. '<li><label for="id_f1">F1:</label> <input id="id_f1" maxlength="30" name="f1" type="text" /></li>'
  3150. '<li><label for="id_f2">F2:</label> <input id="id_f2" maxlength="30" name="f2" type="text" /></li>'
  3151. '<li><label for="id_f3">F3:</label> <textarea cols="40" id="id_f3" name="f3" rows="10">'
  3152. '</textarea></li>'
  3153. '<li><label for="id_f4">F4:</label> <select id="id_f4" name="f4">'
  3154. '<option value="P">Python</option>'
  3155. '<option value="J">Java</option>'
  3156. '</select></li>',
  3157. )
  3158. self.assertHTMLEqual(
  3159. form.as_table(),
  3160. '<tr><th><label for="id_f1">F1:</label></th>'
  3161. '<td><input id="id_f1" maxlength="30" name="f1" type="text" /></td></tr>'
  3162. '<tr><th><label for="id_f2">F2:</label></th>'
  3163. '<td><input id="id_f2" maxlength="30" name="f2" type="text" /></td></tr>'
  3164. '<tr><th><label for="id_f3">F3:</label></th><td><textarea cols="40" id="id_f3" name="f3" rows="10">'
  3165. '</textarea></td></tr>'
  3166. '<tr><th><label for="id_f4">F4:</label></th><td><select id="id_f4" name="f4">'
  3167. '<option value="P">Python</option>'
  3168. '<option value="J">Java</option>'
  3169. '</select></td></tr>',
  3170. )
  3171. def test_only_hidden_fields(self):
  3172. # A form with *only* hidden fields that has errors is going to be very unusual.
  3173. class HiddenForm(Form):
  3174. data = IntegerField(widget=HiddenInput)
  3175. f = HiddenForm({})
  3176. self.assertHTMLEqual(
  3177. f.as_p(),
  3178. '<ul class="errorlist nonfield">'
  3179. '<li>(Hidden field data) This field is required.</li></ul>\n<p> '
  3180. '<input type="hidden" name="data" id="id_data" /></p>'
  3181. )
  3182. self.assertHTMLEqual(
  3183. f.as_table(),
  3184. '<tr><td colspan="2"><ul class="errorlist nonfield">'
  3185. '<li>(Hidden field data) This field is required.</li></ul>'
  3186. '<input type="hidden" name="data" id="id_data" /></td></tr>'
  3187. )
  3188. def test_field_named_data(self):
  3189. class DataForm(Form):
  3190. data = CharField(max_length=10)
  3191. f = DataForm({'data': 'xyzzy'})
  3192. self.assertTrue(f.is_valid())
  3193. self.assertEqual(f.cleaned_data, {'data': 'xyzzy'})
  3194. class CustomRenderer(DjangoTemplates):
  3195. pass
  3196. class RendererTests(SimpleTestCase):
  3197. def test_default(self):
  3198. form = Form()
  3199. self.assertEqual(form.renderer, get_default_renderer())
  3200. def test_kwarg_instance(self):
  3201. custom = CustomRenderer()
  3202. form = Form(renderer=custom)
  3203. self.assertEqual(form.renderer, custom)
  3204. def test_kwarg_class(self):
  3205. custom = CustomRenderer()
  3206. form = Form(renderer=custom)
  3207. self.assertEqual(form.renderer, custom)
  3208. def test_attribute_instance(self):
  3209. class CustomForm(Form):
  3210. default_renderer = DjangoTemplates()
  3211. form = CustomForm()
  3212. self.assertEqual(form.renderer, CustomForm.default_renderer)
  3213. def test_attribute_class(self):
  3214. class CustomForm(Form):
  3215. default_renderer = CustomRenderer
  3216. form = CustomForm()
  3217. self.assertTrue(isinstance(form.renderer, CustomForm.default_renderer))
  3218. def test_attribute_override(self):
  3219. class CustomForm(Form):
  3220. default_renderer = DjangoTemplates()
  3221. custom = CustomRenderer()
  3222. form = CustomForm(renderer=custom)
  3223. self.assertEqual(form.renderer, custom)