forms.txt 107 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468
  1. =================
  2. The forms library
  3. =================
  4. ``django.forms`` is Django's form-handling library.
  5. .. admonition:: Looking for oldforms?
  6. ``django.forms`` was once called ``newforms`` since it replaced Django's
  7. original form/manipulator/validation framework. The old form handling
  8. library is still available as `django.oldforms`_, but will be removed
  9. in a future version of Django.
  10. .. _django.oldforms: ../oldforms/
  11. Overview
  12. ========
  13. ``django.forms`` is intended to handle HTML form display, data processing
  14. (validation) and redisplay. It's what you use if you want to perform
  15. server-side validation for an HTML form.
  16. For example, if your Web site has a contact form that visitors can use to
  17. send you e-mail, you'd use this library to implement the display of the HTML
  18. form fields, along with the form validation. Any time you need to use an HTML
  19. ``<form>``, you can use this library.
  20. The library deals with these concepts:
  21. * **Widget** -- A class that corresponds to an HTML form widget, e.g.
  22. ``<input type="text">`` or ``<textarea>``. This handles rendering of the
  23. widget as HTML.
  24. * **Field** -- A class that is responsible for doing validation, e.g.
  25. an ``EmailField`` that makes sure its data is a valid e-mail address.
  26. * **Form** -- A collection of fields that knows how to validate itself and
  27. display itself as HTML.
  28. * **Media** -- A definition of the CSS and JavaScript resources that are
  29. required to render a form.
  30. The library is decoupled from the other Django components, such as the database
  31. layer, views and templates. It relies only on Django settings, a couple of
  32. ``django.utils`` helper functions and Django's internationalization hooks (but
  33. you're not required to be using internationalization features to use this
  34. library).
  35. Form objects
  36. ============
  37. The primary way of using the ``forms`` library is to create a form object.
  38. Do this by subclassing ``django.forms.Form`` and specifying the form's
  39. fields, in a declarative style that you'll be familiar with if you've used
  40. Django database models. In this section, we'll iteratively develop a form
  41. object that you might use to implement "contact me" functionality on your
  42. personal Web site.
  43. Start with this basic ``Form`` subclass, which we'll call ``ContactForm``::
  44. from django import forms
  45. class ContactForm(forms.Form):
  46. subject = forms.CharField(max_length=100)
  47. message = forms.CharField()
  48. sender = forms.EmailField()
  49. cc_myself = forms.BooleanField(required=False)
  50. A form is composed of ``Field`` objects. In this case, our form has four
  51. fields: ``subject``, ``message``, ``sender`` and ``cc_myself``. We'll explain
  52. the different types of fields -- e.g., ``CharField`` and ``EmailField`` --
  53. shortly.
  54. Creating ``Form`` instances
  55. ---------------------------
  56. A ``Form`` instance is either **bound** to a set of data, or **unbound**.
  57. * If it's **bound** to a set of data, it's capable of validating that data
  58. and rendering the form as HTML with the data displayed in the HTML.
  59. * If it's **unbound**, it cannot do validation (because there's no data to
  60. validate!), but it can still render the blank form as HTML.
  61. To create an unbound ``Form`` instance, simply instantiate the class::
  62. >>> f = ContactForm()
  63. To bind data to a form, pass the data as a dictionary as the first parameter to
  64. your ``Form`` class constructor::
  65. >>> data = {'subject': 'hello',
  66. ... 'message': 'Hi there',
  67. ... 'sender': 'foo@example.com',
  68. ... 'cc_myself': True}
  69. >>> f = ContactForm(data)
  70. In this dictionary, the keys are the field names, which correspond to the
  71. attributes in your ``Form`` class. The values are the data you're trying
  72. to validate. These will usually be strings, but there's no requirement that
  73. they be strings; the type of data you pass depends on the ``Field``, as we'll
  74. see in a moment.
  75. If you need to distinguish between bound and unbound form instances at runtime,
  76. check the value of the form's ``is_bound`` attribute::
  77. >>> f = ContactForm()
  78. >>> f.is_bound
  79. False
  80. >>> f = ContactForm({'subject': 'hello'})
  81. >>> f.is_bound
  82. True
  83. Note that passing an empty dictionary creates a *bound* form with empty data::
  84. >>> f = ContactForm({})
  85. >>> f.is_bound
  86. True
  87. If you have a bound ``Form`` instance and want to change the data somehow, or
  88. if you want to bind an unbound ``Form`` instance to some data, create another
  89. ``Form`` instance. There is no way to change data in a ``Form`` instance. Once
  90. a ``Form`` instance has been created, you should consider its data immutable,
  91. whether it has data or not.
  92. Using forms to validate data
  93. ----------------------------
  94. The primary task of a ``Form`` object is to validate data. With a bound
  95. ``Form`` instance, call the ``is_valid()`` method to run validation and return
  96. a boolean designating whether the data was valid::
  97. >>> data = {'subject': 'hello',
  98. ... 'message': 'Hi there',
  99. ... 'sender': 'foo@example.com',
  100. ... 'cc_myself': True}
  101. >>> f = ContactForm(data)
  102. >>> f.is_valid()
  103. True
  104. Let's try with some invalid data. In this case, ``subject`` is blank (an error,
  105. because all fields are required by default) and ``sender`` is not a valid
  106. e-mail address::
  107. >>> data = {'subject': '',
  108. ... 'message': 'Hi there',
  109. ... 'sender': 'invalid e-mail address',
  110. ... 'cc_myself': True}
  111. >>> f = ContactForm(data)
  112. >>> f.is_valid()
  113. False
  114. Access the ``errors`` attribute to get a dictionary of error messages::
  115. >>> f.errors
  116. {'sender': [u'Enter a valid e-mail address.'], 'subject': [u'This field is required.']}
  117. In this dictionary, the keys are the field names, and the values are lists of
  118. Unicode strings representing the error messages. The error messages are stored
  119. in lists because a field can have multiple error messages.
  120. You can access ``errors`` without having to call ``is_valid()`` first. The
  121. form's data will be validated the first time either you call ``is_valid()`` or
  122. access ``errors``.
  123. The validation routines will only get called once, regardless of how many times
  124. you access ``errors`` or call ``is_valid()``. This means that if validation has
  125. side effects, those side effects will only be triggered once.
  126. Behavior of unbound forms
  127. ~~~~~~~~~~~~~~~~~~~~~~~~~
  128. It's meaningless to validate a form with no data, but, for the record, here's
  129. what happens with unbound forms::
  130. >>> f = ContactForm()
  131. >>> f.is_valid()
  132. False
  133. >>> f.errors
  134. {}
  135. Accessing "clean" data
  136. ----------------------
  137. Each ``Field`` in a ``Form`` class is responsible not only for validating data,
  138. but also for "cleaning" it -- normalizing it to a consistent format. This is a
  139. nice feature, because it allows data for a particular field to be input in
  140. a variety of ways, always resulting in consistent output.
  141. For example, ``DateField`` normalizes input into a Python ``datetime.date``
  142. object. Regardless of whether you pass it a string in the format
  143. ``'1994-07-15'``, a ``datetime.date`` object or a number of other formats,
  144. ``DateField`` will always normalize it to a ``datetime.date`` object as long as
  145. it's valid.
  146. Once you've created a ``Form`` instance with a set of data and validated it,
  147. you can access the clean data via the ``cleaned_data`` attribute of the ``Form``
  148. object::
  149. >>> data = {'subject': 'hello',
  150. ... 'message': 'Hi there',
  151. ... 'sender': 'foo@example.com',
  152. ... 'cc_myself': True}
  153. >>> f = ContactForm(data)
  154. >>> f.is_valid()
  155. True
  156. >>> f.cleaned_data
  157. {'cc_myself': True, 'message': u'Hi there', 'sender': u'foo@example.com', 'subject': u'hello'}
  158. .. note::
  159. **New in Django development version** The ``cleaned_data`` attribute was
  160. called ``clean_data`` in earlier releases.
  161. Note that any text-based field -- such as ``CharField`` or ``EmailField`` --
  162. always cleans the input into a Unicode string. We'll cover the encoding
  163. implications later in this document.
  164. If your data does *not* validate, your ``Form`` instance will not have a
  165. ``cleaned_data`` attribute::
  166. >>> data = {'subject': '',
  167. ... 'message': 'Hi there',
  168. ... 'sender': 'invalid e-mail address',
  169. ... 'cc_myself': True}
  170. >>> f = ContactForm(data)
  171. >>> f.is_valid()
  172. False
  173. >>> f.cleaned_data
  174. Traceback (most recent call last):
  175. ...
  176. AttributeError: 'ContactForm' object has no attribute 'cleaned_data'
  177. ``cleaned_data`` will always *only* contain a key for fields defined in the
  178. ``Form``, even if you pass extra data when you define the ``Form``. In this
  179. example, we pass a bunch of extra fields to the ``ContactForm`` constructor,
  180. but ``cleaned_data`` contains only the form's fields::
  181. >>> data = {'subject': 'hello',
  182. ... 'message': 'Hi there',
  183. ... 'sender': 'foo@example.com',
  184. ... 'cc_myself': True,
  185. ... 'extra_field_1': 'foo',
  186. ... 'extra_field_2': 'bar',
  187. ... 'extra_field_3': 'baz'}
  188. >>> f = ContactForm(data)
  189. >>> f.is_valid()
  190. True
  191. >>> f.cleaned_data # Doesn't contain extra_field_1, etc.
  192. {'cc_myself': True, 'message': u'Hi there', 'sender': u'foo@example.com', 'subject': u'hello'}
  193. ``cleaned_data`` will include a key and value for *all* fields defined in the
  194. ``Form``, even if the data didn't include a value for fields that are not
  195. required. In this example, the data dictionary doesn't include a value for the
  196. ``nick_name`` field, but ``cleaned_data`` includes it, with an empty value::
  197. >>> class OptionalPersonForm(Form):
  198. ... first_name = CharField()
  199. ... last_name = CharField()
  200. ... nick_name = CharField(required=False)
  201. >>> data = {'first_name': u'John', 'last_name': u'Lennon'}
  202. >>> f = OptionalPersonForm(data)
  203. >>> f.is_valid()
  204. True
  205. >>> f.cleaned_data
  206. {'nick_name': u'', 'first_name': u'John', 'last_name': u'Lennon'}
  207. In this above example, the ``cleaned_data`` value for ``nick_name`` is set to an
  208. empty string, because ``nick_name`` is ``CharField``, and ``CharField``\s treat
  209. empty values as an empty string. Each field type knows what its "blank" value
  210. is -- e.g., for ``DateField``, it's ``None`` instead of the empty string. For
  211. full details on each field's behavior in this case, see the "Empty value" note
  212. for each field in the "Built-in ``Field`` classes" section below.
  213. You can write code to perform validation for particular form fields (based on
  214. their name) or for the form as a whole (considering combinations of various
  215. fields). More information about this is in the `Custom form and field
  216. validation`_ section, below.
  217. Behavior of unbound forms
  218. ~~~~~~~~~~~~~~~~~~~~~~~~~
  219. It's meaningless to request "cleaned" data in a form with no data, but, for the
  220. record, here's what happens with unbound forms::
  221. >>> f = ContactForm()
  222. >>> f.cleaned_data
  223. Traceback (most recent call last):
  224. ...
  225. AttributeError: 'ContactForm' object has no attribute 'cleaned_data'
  226. Outputting forms as HTML
  227. ------------------------
  228. The second task of a ``Form`` object is to render itself as HTML. To do so,
  229. simply ``print`` it::
  230. >>> f = ContactForm()
  231. >>> print f
  232. <tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" /></td></tr>
  233. <tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" /></td></tr>
  234. <tr><th><label for="id_sender">Sender:</label></th><td><input type="text" name="sender" id="id_sender" /></td></tr>
  235. <tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" /></td></tr>
  236. If the form is bound to data, the HTML output will include that data
  237. appropriately. For example, if a field is represented by an
  238. ``<input type="text">``, the data will be in the ``value`` attribute. If a
  239. field is represented by an ``<input type="checkbox">``, then that HTML will
  240. include ``checked="checked"`` if appropriate::
  241. >>> data = {'subject': 'hello',
  242. ... 'message': 'Hi there',
  243. ... 'sender': 'foo@example.com',
  244. ... 'cc_myself': True}
  245. >>> f = ContactForm(data)
  246. >>> print f
  247. <tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" value="hello" /></td></tr>
  248. <tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" value="Hi there" /></td></tr>
  249. <tr><th><label for="id_sender">Sender:</label></th><td><input type="text" name="sender" id="id_sender" value="foo@example.com" /></td></tr>
  250. <tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" checked="checked" /></td></tr>
  251. This default output is a two-column HTML table, with a ``<tr>`` for each field.
  252. Notice the following:
  253. * For flexibility, the output does *not* include the ``<table>`` and
  254. ``</table>`` tags, nor does it include the ``<form>`` and ``</form>``
  255. tags or an ``<input type="submit">`` tag. It's your job to do that.
  256. * Each field type has a default HTML representation. ``CharField`` and
  257. ``EmailField`` are represented by an ``<input type="text">``.
  258. ``BooleanField`` is represented by an ``<input type="checkbox">``. Note
  259. these are merely sensible defaults; you can specify which HTML to use for
  260. a given field by using widgets, which we'll explain shortly.
  261. * The HTML ``name`` for each tag is taken directly from its attribute name
  262. in the ``ContactForm`` class.
  263. * The text label for each field -- e.g. ``'Subject:'``, ``'Message:'`` and
  264. ``'Cc myself:'`` is generated from the field name by converting all
  265. underscores to spaces and upper-casing the first letter. Again, note
  266. these are merely sensible defaults; you can also specify labels manually.
  267. * Each text label is surrounded in an HTML ``<label>`` tag, which points
  268. to the appropriate form field via its ``id``. Its ``id``, in turn, is
  269. generated by prepending ``'id_'`` to the field name. The ``id``
  270. attributes and ``<label>`` tags are included in the output by default, to
  271. follow best practices, but you can change that behavior.
  272. Although ``<table>`` output is the default output style when you ``print`` a
  273. form, other output styles are available. Each style is available as a method on
  274. a form object, and each rendering method returns a Unicode object.
  275. ``as_p()``
  276. ~~~~~~~~~~
  277. ``Form.as_p()`` renders the form as a series of ``<p>`` tags, with each ``<p>``
  278. containing one field::
  279. >>> f = ContactForm()
  280. >>> f.as_p()
  281. u'<p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></p>\n<p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></p>\n<p><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" /></p>\n<p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></p>'
  282. >>> print f.as_p()
  283. <p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></p>
  284. <p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></p>
  285. <p><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" /></p>
  286. <p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></p>
  287. ``as_ul()``
  288. ~~~~~~~~~~~
  289. ``Form.as_ul()`` renders the form as a series of ``<li>`` tags, with each
  290. ``<li>`` containing one field. It does *not* include the ``<ul>`` or ``</ul>``,
  291. so that you can specify any HTML attributes on the ``<ul>`` for flexibility::
  292. >>> f = ContactForm()
  293. >>> f.as_ul()
  294. u'<li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></li>\n<li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></li>\n<li><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" /></li>\n<li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></li>'
  295. >>> print f.as_ul()
  296. <li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></li>
  297. <li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></li>
  298. <li><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" /></li>
  299. <li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></li>
  300. ``as_table()``
  301. ~~~~~~~~~~~~~~
  302. Finally, ``Form.as_table()`` outputs the form as an HTML ``<table>``. This is
  303. exactly the same as ``print``. In fact, when you ``print`` a form object, it
  304. calls its ``as_table()`` method behind the scenes::
  305. >>> f = ContactForm()
  306. >>> f.as_table()
  307. u'<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" /></td></tr>\n<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" /></td></tr>\n<tr><th><label for="id_sender">Sender:</label></th><td><input type="text" name="sender" id="id_sender" /></td></tr>\n<tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" /></td></tr>'
  308. >>> print f.as_table()
  309. <tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" /></td></tr>
  310. <tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" /></td></tr>
  311. <tr><th><label for="id_sender">Sender:</label></th><td><input type="text" name="sender" id="id_sender" /></td></tr>
  312. <tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" /></td></tr>
  313. Configuring HTML ``<label>`` tags
  314. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  315. An HTML ``<label>`` tag designates which label text is associated with which
  316. form element. This small enhancement makes forms more usable and more accessible
  317. to assistive devices. It's always a good idea to use ``<label>`` tags.
  318. By default, the form rendering methods include HTML ``id`` attributes on the
  319. form elements and corresponding ``<label>`` tags around the labels. The ``id``
  320. attribute values are generated by prepending ``id_`` to the form field names.
  321. This behavior is configurable, though, if you want to change the ``id``
  322. convention or remove HTML ``id`` attributes and ``<label>`` tags entirely.
  323. Use the ``auto_id`` argument to the ``Form`` constructor to control the label
  324. and ``id`` behavior. This argument must be ``True``, ``False`` or a string.
  325. If ``auto_id`` is ``False``, then the form output will not include ``<label>``
  326. tags nor ``id`` attributes::
  327. >>> f = ContactForm(auto_id=False)
  328. >>> print f.as_table()
  329. <tr><th>Subject:</th><td><input type="text" name="subject" maxlength="100" /></td></tr>
  330. <tr><th>Message:</th><td><input type="text" name="message" /></td></tr>
  331. <tr><th>Sender:</th><td><input type="text" name="sender" /></td></tr>
  332. <tr><th>Cc myself:</th><td><input type="checkbox" name="cc_myself" /></td></tr>
  333. >>> print f.as_ul()
  334. <li>Subject: <input type="text" name="subject" maxlength="100" /></li>
  335. <li>Message: <input type="text" name="message" /></li>
  336. <li>Sender: <input type="text" name="sender" /></li>
  337. <li>Cc myself: <input type="checkbox" name="cc_myself" /></li>
  338. >>> print f.as_p()
  339. <p>Subject: <input type="text" name="subject" maxlength="100" /></p>
  340. <p>Message: <input type="text" name="message" /></p>
  341. <p>Sender: <input type="text" name="sender" /></p>
  342. <p>Cc myself: <input type="checkbox" name="cc_myself" /></p>
  343. If ``auto_id`` is set to ``True``, then the form output *will* include
  344. ``<label>`` tags and will simply use the field name as its ``id`` for each form
  345. field::
  346. >>> f = ContactForm(auto_id=True)
  347. >>> print f.as_table()
  348. <tr><th><label for="subject">Subject:</label></th><td><input id="subject" type="text" name="subject" maxlength="100" /></td></tr>
  349. <tr><th><label for="message">Message:</label></th><td><input type="text" name="message" id="message" /></td></tr>
  350. <tr><th><label for="sender">Sender:</label></th><td><input type="text" name="sender" id="sender" /></td></tr>
  351. <tr><th><label for="cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="cc_myself" /></td></tr>
  352. >>> print f.as_ul()
  353. <li><label for="subject">Subject:</label> <input id="subject" type="text" name="subject" maxlength="100" /></li>
  354. <li><label for="message">Message:</label> <input type="text" name="message" id="message" /></li>
  355. <li><label for="sender">Sender:</label> <input type="text" name="sender" id="sender" /></li>
  356. <li><label for="cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="cc_myself" /></li>
  357. >>> print f.as_p()
  358. <p><label for="subject">Subject:</label> <input id="subject" type="text" name="subject" maxlength="100" /></p>
  359. <p><label for="message">Message:</label> <input type="text" name="message" id="message" /></p>
  360. <p><label for="sender">Sender:</label> <input type="text" name="sender" id="sender" /></p>
  361. <p><label for="cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="cc_myself" /></p>
  362. If ``auto_id`` is set to a string containing the format character ``'%s'``,
  363. then the form output will include ``<label>`` tags, and will generate ``id``
  364. attributes based on the format string. For example, for a format string
  365. ``'field_%s'``, a field named ``subject`` will get the ``id`` value
  366. ``'field_subject'``. Continuing our example::
  367. >>> f = ContactForm(auto_id='id_for_%s')
  368. >>> print f.as_table()
  369. <tr><th><label for="id_for_subject">Subject:</label></th><td><input id="id_for_subject" type="text" name="subject" maxlength="100" /></td></tr>
  370. <tr><th><label for="id_for_message">Message:</label></th><td><input type="text" name="message" id="id_for_message" /></td></tr>
  371. <tr><th><label for="id_for_sender">Sender:</label></th><td><input type="text" name="sender" id="id_for_sender" /></td></tr>
  372. <tr><th><label for="id_for_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_for_cc_myself" /></td></tr>
  373. >>> print f.as_ul()
  374. <li><label for="id_for_subject">Subject:</label> <input id="id_for_subject" type="text" name="subject" maxlength="100" /></li>
  375. <li><label for="id_for_message">Message:</label> <input type="text" name="message" id="id_for_message" /></li>
  376. <li><label for="id_for_sender">Sender:</label> <input type="text" name="sender" id="id_for_sender" /></li>
  377. <li><label for="id_for_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself" /></li>
  378. >>> print f.as_p()
  379. <p><label for="id_for_subject">Subject:</label> <input id="id_for_subject" type="text" name="subject" maxlength="100" /></p>
  380. <p><label for="id_for_message">Message:</label> <input type="text" name="message" id="id_for_message" /></p>
  381. <p><label for="id_for_sender">Sender:</label> <input type="text" name="sender" id="id_for_sender" /></p>
  382. <p><label for="id_for_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself" /></p>
  383. If ``auto_id`` is set to any other true value -- such as a string that doesn't
  384. include ``%s`` -- then the library will act as if ``auto_id`` is ``True``.
  385. By default, ``auto_id`` is set to the string ``'id_%s'``.
  386. Normally, a colon (``:``) will be appended after any label name when a form is
  387. rendered. It's possible to change the colon to another character, or omit it
  388. entirely, using the ``label_suffix`` parameter::
  389. >>> f = ContactForm(auto_id='id_for_%s', label_suffix='')
  390. >>> print f.as_ul()
  391. <li><label for="id_for_subject">Subject</label> <input id="id_for_subject" type="text" name="subject" maxlength="100" /></li>
  392. <li><label for="id_for_message">Message</label> <input type="text" name="message" id="id_for_message" /></li>
  393. <li><label for="id_for_sender">Sender</label> <input type="text" name="sender" id="id_for_sender" /></li>
  394. <li><label for="id_for_cc_myself">Cc myself</label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself" /></li>
  395. >>> f = ContactForm(auto_id='id_for_%s', label_suffix=' ->')
  396. >>> print f.as_ul()
  397. <li><label for="id_for_subject">Subject -></label> <input id="id_for_subject" type="text" name="subject" maxlength="100" /></li>
  398. <li><label for="id_for_message">Message -></label> <input type="text" name="message" id="id_for_message" /></li>
  399. <li><label for="id_for_sender">Sender -></label> <input type="text" name="sender" id="id_for_sender" /></li>
  400. <li><label for="id_for_cc_myself">Cc myself -></label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself" /></li>
  401. Note that the label suffix is added only if the last character of the
  402. label isn't a punctuation character (``.``, ``!``, ``?`` or ``:``)
  403. Notes on field ordering
  404. ~~~~~~~~~~~~~~~~~~~~~~~
  405. In the ``as_p()``, ``as_ul()`` and ``as_table()`` shortcuts, the fields are
  406. displayed in the order in which you define them in your form class. For
  407. example, in the ``ContactForm`` example, the fields are defined in the order
  408. ``subject``, ``message``, ``sender``, ``cc_myself``. To reorder the HTML
  409. output, just change the order in which those fields are listed in the class.
  410. How errors are displayed
  411. ~~~~~~~~~~~~~~~~~~~~~~~~
  412. If you render a bound ``Form`` object, the act of rendering will automatically
  413. run the form's validation if it hasn't already happened, and the HTML output
  414. will include the validation errors as a ``<ul class="errorlist">`` near the
  415. field. The particular positioning of the error messages depends on the output
  416. method you're using::
  417. >>> data = {'subject': '',
  418. ... 'message': 'Hi there',
  419. ... 'sender': 'invalid e-mail address',
  420. ... 'cc_myself': True}
  421. >>> f = ContactForm(data, auto_id=False)
  422. >>> print f.as_table()
  423. <tr><th>Subject:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="subject" maxlength="100" /></td></tr>
  424. <tr><th>Message:</th><td><input type="text" name="message" value="Hi there" /></td></tr>
  425. <tr><th>Sender:</th><td><ul class="errorlist"><li>Enter a valid e-mail address.</li></ul><input type="text" name="sender" value="invalid e-mail address" /></td></tr>
  426. <tr><th>Cc myself:</th><td><input checked="checked" type="checkbox" name="cc_myself" /></td></tr>
  427. >>> print f.as_ul()
  428. <li><ul class="errorlist"><li>This field is required.</li></ul>Subject: <input type="text" name="subject" maxlength="100" /></li>
  429. <li>Message: <input type="text" name="message" value="Hi there" /></li>
  430. <li><ul class="errorlist"><li>Enter a valid e-mail address.</li></ul>Sender: <input type="text" name="sender" value="invalid e-mail address" /></li>
  431. <li>Cc myself: <input checked="checked" type="checkbox" name="cc_myself" /></li>
  432. >>> print f.as_p()
  433. <p><ul class="errorlist"><li>This field is required.</li></ul></p>
  434. <p>Subject: <input type="text" name="subject" maxlength="100" /></p>
  435. <p>Message: <input type="text" name="message" value="Hi there" /></p>
  436. <p><ul class="errorlist"><li>Enter a valid e-mail address.</li></ul></p>
  437. <p>Sender: <input type="text" name="sender" value="invalid e-mail address" /></p>
  438. <p>Cc myself: <input checked="checked" type="checkbox" name="cc_myself" /></p>
  439. Customizing the error list format
  440. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  441. By default, forms use ``django.forms.util.ErrorList`` to format validation
  442. errors. If you'd like to use an alternate class for displaying errors, you can
  443. pass that in at construction time::
  444. >>> from django.forms.util import ErrorList
  445. >>> class DivErrorList(ErrorList):
  446. ... def __unicode__(self):
  447. ... return self.as_divs()
  448. ... def as_divs(self):
  449. ... if not self: return u''
  450. ... return u'<div class="errorlist">%s</div>' % ''.join([u'<div class="error">%s</div>' % e for e in self])
  451. >>> f = ContactForm(data, auto_id=False, error_class=DivErrorList)
  452. >>> f.as_p()
  453. <div class="errorlist"><div class="error">This field is required.</div></div>
  454. <p>Subject: <input type="text" name="subject" maxlength="100" /></p>
  455. <p>Message: <input type="text" name="message" value="Hi there" /></p>
  456. <div class="errorlist"><div class="error">Enter a valid e-mail address.</div></div>
  457. <p>Sender: <input type="text" name="sender" value="invalid e-mail address" /></p>
  458. <p>Cc myself: <input checked="checked" type="checkbox" name="cc_myself" /></p>
  459. More granular output
  460. ~~~~~~~~~~~~~~~~~~~~
  461. The ``as_p()``, ``as_ul()`` and ``as_table()`` methods are simply shortcuts for
  462. lazy developers -- they're not the only way a form object can be displayed.
  463. To display the HTML for a single field in your form, use dictionary lookup
  464. syntax using the field's name as the key, and print the resulting object::
  465. >>> f = ContactForm()
  466. >>> print f['subject']
  467. <input id="id_subject" type="text" name="subject" maxlength="100" />
  468. >>> print f['message']
  469. <input type="text" name="message" id="id_message" />
  470. >>> print f['sender']
  471. <input type="text" name="sender" id="id_sender" />
  472. >>> print f['cc_myself']
  473. <input type="checkbox" name="cc_myself" id="id_cc_myself" />
  474. Call ``str()`` or ``unicode()`` on the field to get its rendered HTML as a
  475. string or Unicode object, respectively::
  476. >>> str(f['subject'])
  477. '<input id="id_subject" type="text" name="subject" maxlength="100" />'
  478. >>> unicode(f['subject'])
  479. u'<input id="id_subject" type="text" name="subject" maxlength="100" />'
  480. The field-specific output honors the form object's ``auto_id`` setting::
  481. >>> f = ContactForm(auto_id=False)
  482. >>> print f['message']
  483. <input type="text" name="message" />
  484. >>> f = ContactForm(auto_id='id_%s')
  485. >>> print f['message']
  486. <input type="text" name="message" id="id_message" />
  487. For a field's list of errors, access the field's ``errors`` attribute. This
  488. is a list-like object that is displayed as an HTML ``<ul class="errorlist">``
  489. when printed::
  490. >>> data = {'subject': 'hi', 'message': '', 'sender': '', 'cc_myself': ''}
  491. >>> f = ContactForm(data, auto_id=False)
  492. >>> print f['message']
  493. <input type="text" name="message" />
  494. >>> f['message'].errors
  495. [u'This field is required.']
  496. >>> print f['message'].errors
  497. <ul class="errorlist"><li>This field is required.</li></ul>
  498. >>> f['subject'].errors
  499. []
  500. >>> print f['subject'].errors
  501. >>> str(f['subject'].errors)
  502. ''
  503. Using forms in views and templates
  504. ----------------------------------
  505. Let's put this all together and use the ``ContactForm`` example in a Django
  506. view and template.
  507. Simple view example
  508. ~~~~~~~~~~~~~~~~~~~
  509. This example view displays the contact form by default and validates/processes
  510. it if accessed via a POST request::
  511. def contact(request):
  512. if request.method == 'POST':
  513. form = ContactForm(request.POST)
  514. if form.is_valid():
  515. # Do form processing here...
  516. return HttpResponseRedirect('/url/on_success/')
  517. else:
  518. form = ContactForm()
  519. return render_to_response('contact.html', {'form': form})
  520. Simple template example
  521. ~~~~~~~~~~~~~~~~~~~~~~~
  522. The template in the above view example, ``contact.html``, is responsible for
  523. displaying the form as HTML. To do this, we can use the techniques outlined in
  524. the "Outputting forms as HTML" section above.
  525. The simplest way to display a form's HTML is to use the variable on its own,
  526. like this::
  527. <form method="post" action="">
  528. <table>{{ form }}</table>
  529. <input type="submit" />
  530. </form>
  531. The above template code will display the form as an HTML table, using the
  532. ``form.as_table()`` method explained previously. This works because Django's
  533. template system displays an object's ``__str__()`` value, and the ``Form``
  534. class' ``__str__()`` method calls its ``as_table()`` method.
  535. The following is equivalent but a bit more explicit::
  536. <form method="post" action="">
  537. <table>{{ form.as_table }}</table>
  538. <input type="submit" />
  539. </form>
  540. ``form.as_ul`` and ``form.as_p`` are also available, as you may expect.
  541. Note that in the above two examples, we included the ``<form>``, ``<table>``
  542. ``<input type="submit" />``, ``</table>`` and ``</form>`` tags. The form
  543. convenience methods (``as_table()``, ``as_ul()`` and ``as_p()``) do not include
  544. that HTML.
  545. Complex template output
  546. ~~~~~~~~~~~~~~~~~~~~~~~
  547. As we've stressed several times, the ``as_table()``, ``as_ul()`` and ``as_p()``
  548. methods are just shortcuts for the common case. You can also work with the
  549. individual fields for complete template control over the form's design.
  550. The easiest way is to iterate over the form's fields, with
  551. ``{% for field in form %}``. For example::
  552. <form method="post" action="">
  553. <dl>
  554. {% for field in form %}
  555. <dt>{{ field.label_tag }}</dt>
  556. <dd>{{ field }}</dd>
  557. {% if field.help_text %}<dd>{{ field.help_text }}</dd>{% endif %}
  558. {% if field.errors %}<dd class="myerrors">{{ field.errors }}</dd>{% endif %}
  559. {% endfor %}
  560. </dl>
  561. <input type="submit" />
  562. </form>
  563. This iteration technique is useful if you want to apply the same HTML
  564. formatting to each field, or if you don't know the names of the form fields
  565. ahead of time. Note that the fields will be iterated over in the order in which
  566. they're defined in the ``Form`` class.
  567. Alternatively, you can arrange the form's fields explicitly, by name. Do that
  568. by accessing ``{{ form.fieldname }}``, where ``fieldname`` is the field's name.
  569. For example::
  570. <form method="post" action="">
  571. <ul class="myformclass">
  572. <li>{{ form.sender.label_tag }} {{ form.sender }}</li>
  573. <li class="helptext">{{ form.sender.help_text }}</li>
  574. {% if form.sender.errors %}<ul class="errorlist">{{ form.sender.errors }}</ul>{% endif %}
  575. <li>{{ form.subject.label_tag }} {{ form.subject }}</li>
  576. <li class="helptext">{{ form.subject.help_text }}</li>
  577. {% if form.subject.errors %}<ul class="errorlist">{{ form.subject.errors }}</ul>{% endif %}
  578. ...
  579. </ul>
  580. </form>
  581. Highlighting required fields in templates
  582. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  583. It's common to show a user which fields are required. Here's an example of how
  584. to do that, using the above example modified to insert an asterisk after the
  585. label of each required field::
  586. <form method="post" action="">
  587. <dl>
  588. {% for field in form %}
  589. <dt>{{ field.label_tag }}{% if field.field.required %}*{% endif %}</dt>
  590. <dd>{{ field }}</dd>
  591. {% if field.help_text %}<dd>{{ field.help_text }}</dd>{% endif %}
  592. {% if field.errors %}<dd class="myerrors">{{ field.errors }}</dd>{% endif %}
  593. {% endfor %}
  594. </dl>
  595. <input type="submit" />
  596. </form>
  597. The ``{% if field.field.required %}*{% endif %}`` fragment is the relevant
  598. addition here. It adds the asterisk only if the field is required.
  599. Note that we check ``field.field.required`` and not ``field.required``. In the
  600. template, ``field`` is a ``forms.forms.BoundField`` instance, which holds
  601. the actual ``Field`` instance in its ``field`` attribute.
  602. Binding uploaded files to a form
  603. --------------------------------
  604. **New in Django development version**
  605. Dealing with forms that have ``FileField`` and ``ImageField`` fields
  606. is a little more complicated than a normal form.
  607. Firstly, in order to upload files, you'll need to make sure that your
  608. ``<form>`` element correctly defines the ``enctype`` as
  609. ``"multipart/form-data"``::
  610. <form enctype="multipart/form-data" method="post" action="/foo/">
  611. Secondly, when you use the form, you need to bind the file data. File
  612. data is handled separately to normal form data, so when your form
  613. contains a ``FileField`` and ``ImageField``, you will need to specify
  614. a second argument when you bind your form. So if we extend our
  615. ContactForm to include an ``ImageField`` called ``mugshot``, we
  616. need to bind the file data containing the mugshot image::
  617. # Bound form with an image field
  618. >>> from django.core.files.uploadedfile import SimpleUploadedFile
  619. >>> data = {'subject': 'hello',
  620. ... 'message': 'Hi there',
  621. ... 'sender': 'foo@example.com',
  622. ... 'cc_myself': True}
  623. >>> file_data = {'mugshot': SimpleUploadedFile('face.jpg', <file data>)}
  624. >>> f = ContactFormWithMugshot(data, file_data)
  625. In practice, you will usually specify ``request.FILES`` as the source
  626. of file data (just like you use ``request.POST`` as the source of
  627. form data)::
  628. # Bound form with an image field, data from the request
  629. >>> f = ContactFormWithMugshot(request.POST, request.FILES)
  630. Constructing an unbound form is the same as always -- just omit both
  631. form data *and* file data::
  632. # Unbound form with a image field
  633. >>> f = ContactFormWithMugshot()
  634. Testing for multipart forms
  635. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  636. If you're writing reusable views or templates, you may not know ahead of time
  637. whether your form is a multipart form or not. The ``is_multipart()`` method
  638. tells you whether the form requires multipart encoding for submission::
  639. >>> f = ContactFormWithMugshot()
  640. >>> f.is_multipart()
  641. True
  642. Here's an example of how you might use this in a template::
  643. {% if form.is_multipart %}
  644. <form enctype="multipart/form-data" method="post" action="/foo/">
  645. {% else %}
  646. <form method="post" action="/foo/">
  647. {% endif %}
  648. {{ form }}
  649. </form>
  650. Subclassing forms
  651. -----------------
  652. If you have multiple ``Form`` classes that share fields, you can use
  653. subclassing to remove redundancy.
  654. When you subclass a custom ``Form`` class, the resulting subclass will
  655. include all fields of the parent class(es), followed by the fields you define
  656. in the subclass.
  657. In this example, ``ContactFormWithPriority`` contains all the fields from
  658. ``ContactForm``, plus an additional field, ``priority``. The ``ContactForm``
  659. fields are ordered first::
  660. >>> class ContactFormWithPriority(ContactForm):
  661. ... priority = forms.CharField()
  662. >>> f = ContactFormWithPriority(auto_id=False)
  663. >>> print f.as_ul()
  664. <li>Subject: <input type="text" name="subject" maxlength="100" /></li>
  665. <li>Message: <input type="text" name="message" /></li>
  666. <li>Sender: <input type="text" name="sender" /></li>
  667. <li>Cc myself: <input type="checkbox" name="cc_myself" /></li>
  668. <li>Priority: <input type="text" name="priority" /></li>
  669. It's possible to subclass multiple forms, treating forms as "mix-ins." In this
  670. example, ``BeatleForm`` subclasses both ``PersonForm`` and ``InstrumentForm``
  671. (in that order), and its field list includes the fields from the parent
  672. classes::
  673. >>> class PersonForm(Form):
  674. ... first_name = CharField()
  675. ... last_name = CharField()
  676. >>> class InstrumentForm(Form):
  677. ... instrument = CharField()
  678. >>> class BeatleForm(PersonForm, InstrumentForm):
  679. ... haircut_type = CharField()
  680. >>> b = BeatleForm(auto_id=False)
  681. >>> print b.as_ul()
  682. <li>First name: <input type="text" name="first_name" /></li>
  683. <li>Last name: <input type="text" name="last_name" /></li>
  684. <li>Instrument: <input type="text" name="instrument" /></li>
  685. <li>Haircut type: <input type="text" name="haircut_type" /></li>
  686. Prefixes for forms
  687. ------------------
  688. You can put several Django forms inside one ``<form>`` tag. To give each
  689. ``Form`` its own namespace, use the ``prefix`` keyword argument::
  690. >>> mother = PersonForm(prefix="mother")
  691. >>> father = PersonForm(prefix="father")
  692. >>> print mother.as_ul()
  693. <li><label for="id_mother-first_name">First name:</label> <input type="text" name="mother-first_name" id="id_mother-first_name" /></li>
  694. <li><label for="id_mother-last_name">Last name:</label> <input type="text" name="mother-last_name" id="id_mother-last_name" /></li>
  695. >>> print father.as_ul()
  696. <li><label for="id_father-first_name">First name:</label> <input type="text" name="father-first_name" id="id_father-first_name" /></li>
  697. <li><label for="id_father-last_name">Last name:</label> <input type="text" name="father-last_name" id="id_father-last_name" /></li>
  698. Fields
  699. ======
  700. When you create a ``Form`` class, the most important part is defining the
  701. fields of the form. Each field has custom validation logic, along with a few
  702. other hooks.
  703. Although the primary way you'll use ``Field`` classes is in ``Form`` classes,
  704. you can also instantiate them and use them directly to get a better idea of
  705. how they work. Each ``Field`` instance has a ``clean()`` method, which takes
  706. a single argument and either raises a ``django.forms.ValidationError``
  707. exception or returns the clean value::
  708. >>> f = forms.EmailField()
  709. >>> f.clean('foo@example.com')
  710. u'foo@example.com'
  711. >>> f.clean(u'foo@example.com')
  712. u'foo@example.com'
  713. >>> f.clean('invalid e-mail address')
  714. Traceback (most recent call last):
  715. ...
  716. ValidationError: [u'Enter a valid e-mail address.']
  717. If you've used Django's old forms/validation framework, take care in noticing
  718. this ``ValidationError`` is different than the previous ``ValidationError``.
  719. This one lives at ``django.forms.ValidationError`` rather than
  720. ``django.core.validators.ValidationError``.
  721. Core field arguments
  722. --------------------
  723. Each ``Field`` class constructor takes at least these arguments. Some
  724. ``Field`` classes take additional, field-specific arguments, but the following
  725. should *always* be accepted:
  726. ``required``
  727. ~~~~~~~~~~~~
  728. By default, each ``Field`` class assumes the value is required, so if you pass
  729. an empty value -- either ``None`` or the empty string (``""``) -- then
  730. ``clean()`` will raise a ``ValidationError`` exception::
  731. >>> f = forms.CharField()
  732. >>> f.clean('foo')
  733. u'foo'
  734. >>> f.clean('')
  735. Traceback (most recent call last):
  736. ...
  737. ValidationError: [u'This field is required.']
  738. >>> f.clean(None)
  739. Traceback (most recent call last):
  740. ...
  741. ValidationError: [u'This field is required.']
  742. >>> f.clean(' ')
  743. u' '
  744. >>> f.clean(0)
  745. u'0'
  746. >>> f.clean(True)
  747. u'True'
  748. >>> f.clean(False)
  749. u'False'
  750. To specify that a field is *not* required, pass ``required=False`` to the
  751. ``Field`` constructor::
  752. >>> f = forms.CharField(required=False)
  753. >>> f.clean('foo')
  754. u'foo'
  755. >>> f.clean('')
  756. u''
  757. >>> f.clean(None)
  758. u''
  759. >>> f.clean(0)
  760. u'0'
  761. >>> f.clean(True)
  762. u'True'
  763. >>> f.clean(False)
  764. u'False'
  765. If a ``Field`` has ``required=False`` and you pass ``clean()`` an empty value,
  766. then ``clean()`` will return a *normalized* empty value rather than raising
  767. ``ValidationError``. For ``CharField``, this will be a Unicode empty string.
  768. For other ``Field`` classes, it might be ``None``. (This varies from field to
  769. field.)
  770. ``label``
  771. ~~~~~~~~~
  772. The ``label`` argument lets you specify the "human-friendly" label for this
  773. field. This is used when the ``Field`` is displayed in a ``Form``.
  774. As explained in "Outputting forms as HTML" above, the default label for a
  775. ``Field`` is generated from the field name by converting all underscores to
  776. spaces and upper-casing the first letter. Specify ``label`` if that default
  777. behavior doesn't result in an adequate label.
  778. Here's a full example ``Form`` that implements ``label`` for two of its fields.
  779. We've specified ``auto_id=False`` to simplify the output::
  780. >>> class CommentForm(forms.Form):
  781. ... name = forms.CharField(label='Your name')
  782. ... url = forms.URLField(label='Your Web site', required=False)
  783. ... comment = forms.CharField()
  784. >>> f = CommentForm(auto_id=False)
  785. >>> print f
  786. <tr><th>Your name:</th><td><input type="text" name="name" /></td></tr>
  787. <tr><th>Your Web site:</th><td><input type="text" name="url" /></td></tr>
  788. <tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr>
  789. ``initial``
  790. ~~~~~~~~~~~
  791. The ``initial`` argument lets you specify the initial value to use when
  792. rendering this ``Field`` in an unbound ``Form``.
  793. The use-case for this is when you want to display an "empty" form in which a
  794. field is initialized to a particular value. For example::
  795. >>> class CommentForm(forms.Form):
  796. ... name = forms.CharField(initial='Your name')
  797. ... url = forms.URLField(initial='http://')
  798. ... comment = forms.CharField()
  799. >>> f = CommentForm(auto_id=False)
  800. >>> print f
  801. <tr><th>Name:</th><td><input type="text" name="name" value="Your name" /></td></tr>
  802. <tr><th>Url:</th><td><input type="text" name="url" value="http://" /></td></tr>
  803. <tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr>
  804. You may be thinking, why not just pass a dictionary of the initial values as
  805. data when displaying the form? Well, if you do that, you'll trigger validation,
  806. and the HTML output will include any validation errors::
  807. >>> class CommentForm(forms.Form):
  808. ... name = forms.CharField()
  809. ... url = forms.URLField()
  810. ... comment = forms.CharField()
  811. >>> default_data = {'name': 'Your name', 'url': 'http://'}
  812. >>> f = CommentForm(default_data, auto_id=False)
  813. >>> print f
  814. <tr><th>Name:</th><td><input type="text" name="name" value="Your name" /></td></tr>
  815. <tr><th>Url:</th><td><ul class="errorlist"><li>Enter a valid URL.</li></ul><input type="text" name="url" value="http://" /></td></tr>
  816. <tr><th>Comment:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="comment" /></td></tr>
  817. This is why ``initial`` values are only displayed for unbound forms. For bound
  818. forms, the HTML output will use the bound data.
  819. Also note that ``initial`` values are *not* used as "fallback" data in
  820. validation if a particular field's value is not given. ``initial`` values are
  821. *only* intended for initial form display::
  822. >>> class CommentForm(forms.Form):
  823. ... name = forms.CharField(initial='Your name')
  824. ... url = forms.URLField(initial='http://')
  825. ... comment = forms.CharField()
  826. >>> data = {'name': '', 'url': '', 'comment': 'Foo'}
  827. >>> f = CommentForm(data)
  828. >>> f.is_valid()
  829. False
  830. # The form does *not* fall back to using the initial values.
  831. >>> f.errors
  832. {'url': [u'This field is required.'], 'name': [u'This field is required.']}
  833. ``widget``
  834. ~~~~~~~~~~
  835. The ``widget`` argument lets you specify a ``Widget`` class to use when
  836. rendering this ``Field``. See `Widgets`_ below for more information.
  837. ``help_text``
  838. ~~~~~~~~~~~~~
  839. The ``help_text`` argument lets you specify descriptive text for this
  840. ``Field``. If you provide ``help_text``, it will be displayed next to the
  841. ``Field`` when the ``Field`` is rendered by one of the convenience ``Form``
  842. methods (e.g., ``as_ul()``).
  843. Here's a full example ``Form`` that implements ``help_text`` for two of its
  844. fields. We've specified ``auto_id=False`` to simplify the output::
  845. >>> class HelpTextContactForm(forms.Form):
  846. ... subject = forms.CharField(max_length=100, help_text='100 characters max.')
  847. ... message = forms.CharField()
  848. ... sender = forms.EmailField(help_text='A valid e-mail address, please.')
  849. ... cc_myself = forms.BooleanField(required=False)
  850. >>> f = HelpTextContactForm(auto_id=False)
  851. >>> print f.as_table()
  852. <tr><th>Subject:</th><td><input type="text" name="subject" maxlength="100" /><br />100 characters max.</td></tr>
  853. <tr><th>Message:</th><td><input type="text" name="message" /></td></tr>
  854. <tr><th>Sender:</th><td><input type="text" name="sender" /><br />A valid e-mail address, please.</td></tr>
  855. <tr><th>Cc myself:</th><td><input type="checkbox" name="cc_myself" /></td></tr>
  856. >>> print f.as_ul()
  857. <li>Subject: <input type="text" name="subject" maxlength="100" /> 100 characters max.</li>
  858. <li>Message: <input type="text" name="message" /></li>
  859. <li>Sender: <input type="text" name="sender" /> A valid e-mail address, please.</li>
  860. <li>Cc myself: <input type="checkbox" name="cc_myself" /></li>
  861. >>> print f.as_p()
  862. <p>Subject: <input type="text" name="subject" maxlength="100" /> 100 characters max.</p>
  863. <p>Message: <input type="text" name="message" /></p>
  864. <p>Sender: <input type="text" name="sender" /> A valid e-mail address, please.</p>
  865. <p>Cc myself: <input type="checkbox" name="cc_myself" /></p>
  866. ``error_messages``
  867. ~~~~~~~~~~~~~~~~~~
  868. **New in Django development version**
  869. The ``error_messages`` argument lets you override the default messages that the
  870. field will raise. Pass in a dictionary with keys matching the error messages you
  871. want to override. For example, here is the default error message::
  872. >>> generic = forms.CharField()
  873. >>> generic.clean('')
  874. Traceback (most recent call last):
  875. ...
  876. ValidationError: [u'This field is required.']
  877. And here is a custom error message::
  878. >>> name = forms.CharField(error_messages={'required': 'Please enter your name'})
  879. >>> name.clean('')
  880. Traceback (most recent call last):
  881. ...
  882. ValidationError: [u'Please enter your name']
  883. In the `built-in Field classes`_ section below, each ``Field`` defines the
  884. error message keys it uses.
  885. Dynamic initial values
  886. ----------------------
  887. The ``initial`` argument to ``Field`` (explained above) lets you hard-code the
  888. initial value for a ``Field`` -- but what if you want to declare the initial
  889. value at runtime? For example, you might want to fill in a ``username`` field
  890. with the username of the current session.
  891. To accomplish this, use the ``initial`` argument to a ``Form``. This argument,
  892. if given, should be a dictionary mapping field names to initial values. Only
  893. include the fields for which you're specifying an initial value; it's not
  894. necessary to include every field in your form. For example::
  895. >>> class CommentForm(forms.Form):
  896. ... name = forms.CharField()
  897. ... url = forms.URLField()
  898. ... comment = forms.CharField()
  899. >>> f = CommentForm(initial={'name': 'your username'}, auto_id=False)
  900. >>> print f
  901. <tr><th>Name:</th><td><input type="text" name="name" value="your username" /></td></tr>
  902. <tr><th>Url:</th><td><input type="text" name="url" /></td></tr>
  903. <tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr>
  904. >>> f = CommentForm(initial={'name': 'another username'}, auto_id=False)
  905. >>> print f
  906. <tr><th>Name:</th><td><input type="text" name="name" value="another username" /></td></tr>
  907. <tr><th>Url:</th><td><input type="text" name="url" /></td></tr>
  908. <tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr>
  909. Just like the ``initial`` parameter to ``Field``, these values are only
  910. displayed for unbound forms, and they're not used as fallback values if a
  911. particular value isn't provided.
  912. Finally, note that if a ``Field`` defines ``initial`` *and* you include
  913. ``initial`` when instantiating the ``Form``, then the latter ``initial`` will
  914. have precedence. In this example, ``initial`` is provided both at the field
  915. level and at the form instance level, and the latter gets precedence::
  916. >>> class CommentForm(forms.Form):
  917. ... name = forms.CharField(initial='class')
  918. ... url = forms.URLField()
  919. ... comment = forms.CharField()
  920. >>> f = CommentForm(initial={'name': 'instance'}, auto_id=False)
  921. >>> print f
  922. <tr><th>Name:</th><td><input type="text" name="name" value="instance" /></td></tr>
  923. <tr><th>Url:</th><td><input type="text" name="url" /></td></tr>
  924. <tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr>
  925. Built-in ``Field`` classes
  926. --------------------------
  927. Naturally, the ``forms`` library comes with a set of ``Field`` classes that
  928. represent common validation needs. This section documents each built-in field.
  929. For each field, we describe the default widget used if you don't specify
  930. ``widget``. We also specify the value returned when you provide an empty value
  931. (see the section on ``required`` above to understand what that means).
  932. ``BooleanField``
  933. ~~~~~~~~~~~~~~~~
  934. * Default widget: ``CheckboxInput``
  935. * Empty value: ``False``
  936. * Normalizes to: A Python ``True`` or ``False`` value.
  937. * Validates that the check box is checked (i.e. the value is ``True``) if
  938. the field has ``required=True``.
  939. * Error message keys: ``required``
  940. **New in Django development version:** The empty value for a ``CheckboxInput``
  941. (and hence the standard ``BooleanField``) has changed to return ``False``
  942. instead of ``None`` in the development version.
  943. .. note::
  944. Since all ``Field`` subclasses have ``required=True`` by default, the
  945. validation condition here is important. If you want to include a checkbox
  946. in your form that can be either checked or unchecked, you must remember to
  947. pass in ``required=False`` when creating the ``BooleanField``.
  948. ``CharField``
  949. ~~~~~~~~~~~~~
  950. * Default widget: ``TextInput``
  951. * Empty value: ``''`` (an empty string)
  952. * Normalizes to: A Unicode object.
  953. * Validates ``max_length`` or ``min_length``, if they are provided.
  954. Otherwise, all inputs are valid.
  955. * Error message keys: ``required``, ``max_length``, ``min_length``
  956. Has two optional arguments for validation, ``max_length`` and ``min_length``.
  957. If provided, these arguments ensure that the string is at most or at least the
  958. given length.
  959. ``ChoiceField``
  960. ~~~~~~~~~~~~~~~
  961. * Default widget: ``Select``
  962. * Empty value: ``''`` (an empty string)
  963. * Normalizes to: A Unicode object.
  964. * Validates that the given value exists in the list of choices.
  965. * Error message keys: ``required``, ``invalid_choice``
  966. Takes one extra argument, ``choices``, which is an iterable (e.g., a list or
  967. tuple) of 2-tuples to use as choices for this field. This argument accepts
  968. the same formats as the ``choices`` argument to a model field. See the
  969. `model API documentation on choices`_ for more details.
  970. .. _model API documentation on choices: ../model-api#choices
  971. ``DateField``
  972. ~~~~~~~~~~~~~
  973. * Default widget: ``TextInput``
  974. * Empty value: ``None``
  975. * Normalizes to: A Python ``datetime.date`` object.
  976. * Validates that the given value is either a ``datetime.date``,
  977. ``datetime.datetime`` or string formatted in a particular date format.
  978. * Error message keys: ``required``, ``invalid``
  979. Takes one optional argument, ``input_formats``, which is a list of formats used
  980. to attempt to convert a string to a valid ``datetime.date`` object.
  981. If no ``input_formats`` argument is provided, the default input formats are::
  982. '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06'
  983. '%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006'
  984. '%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006'
  985. '%B %d %Y', '%B %d, %Y', # 'October 25 2006', 'October 25, 2006'
  986. '%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006'
  987. ``DateTimeField``
  988. ~~~~~~~~~~~~~~~~~
  989. * Default widget: ``DateTimeInput``
  990. * Empty value: ``None``
  991. * Normalizes to: A Python ``datetime.datetime`` object.
  992. * Validates that the given value is either a ``datetime.datetime``,
  993. ``datetime.date`` or string formatted in a particular datetime format.
  994. * Error message keys: ``required``, ``invalid``
  995. Takes one optional argument, ``input_formats``, which is a list of formats used
  996. to attempt to convert a string to a valid ``datetime.datetime`` object.
  997. If no ``input_formats`` argument is provided, the default input formats are::
  998. '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59'
  999. '%Y-%m-%d %H:%M', # '2006-10-25 14:30'
  1000. '%Y-%m-%d', # '2006-10-25'
  1001. '%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59'
  1002. '%m/%d/%Y %H:%M', # '10/25/2006 14:30'
  1003. '%m/%d/%Y', # '10/25/2006'
  1004. '%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59'
  1005. '%m/%d/%y %H:%M', # '10/25/06 14:30'
  1006. '%m/%d/%y', # '10/25/06'
  1007. **New in Django development version:** The ``DateTimeField`` used to use a
  1008. ``TextInput`` widget by default. This has now changed.
  1009. ``DecimalField``
  1010. ~~~~~~~~~~~~~~~~
  1011. **New in Django development version**
  1012. * Default widget: ``TextInput``
  1013. * Empty value: ``None``
  1014. * Normalizes to: A Python ``decimal``.
  1015. * Validates that the given value is a decimal. Leading and trailing
  1016. whitespace is ignored.
  1017. * Error message keys: ``required``, ``invalid``, ``max_value``,
  1018. ``min_value``, ``max_digits``, ``max_decimal_places``,
  1019. ``max_whole_digits``
  1020. Takes four optional arguments: ``max_value``, ``min_value``, ``max_digits``,
  1021. and ``decimal_places``. The first two define the limits for the fields value.
  1022. ``max_digits`` is the maximum number of digits (those before the decimal
  1023. point plus those after the decimal point, with leading zeros stripped)
  1024. permitted in the value, whilst ``decimal_places`` is the maximum number of
  1025. decimal places permitted.
  1026. ``EmailField``
  1027. ~~~~~~~~~~~~~~
  1028. * Default widget: ``TextInput``
  1029. * Empty value: ``''`` (an empty string)
  1030. * Normalizes to: A Unicode object.
  1031. * Validates that the given value is a valid e-mail address, using a
  1032. moderately complex regular expression.
  1033. * Error message keys: ``required``, ``invalid``
  1034. Has two optional arguments for validation, ``max_length`` and ``min_length``.
  1035. If provided, these arguments ensure that the string is at most or at least the
  1036. given length.
  1037. ``FileField``
  1038. ~~~~~~~~~~~~~
  1039. **New in Django development version**
  1040. * Default widget: ``FileInput``
  1041. * Empty value: ``None``
  1042. * Normalizes to: An ``UploadedFile`` object that wraps the file content
  1043. and file name into a single object.
  1044. * Validates that non-empty file data has been bound to the form.
  1045. * Error message keys: ``required``, ``invalid``, ``missing``, ``empty``
  1046. To learn more about the ``UploadedFile`` object, see the `file uploads documentation`_.
  1047. When you use a ``FileField`` in a form, you must also remember to
  1048. `bind the file data to the form`_.
  1049. .. _file uploads documentation: ../upload_handling/
  1050. .. _`bind the file data to the form`: `Binding uploaded files to a form`_
  1051. ``FilePathField``
  1052. ~~~~~~~~~~~~~~~~~
  1053. **New in Django development version**
  1054. * Default widget: ``Select``
  1055. * Empty value: ``None``
  1056. * Normalizes to: A unicode object
  1057. * Validates that the selected choice exists in the list of choices.
  1058. * Error message keys: ``required``, ``invalid_choice``
  1059. The field allows choosing from files inside a certain directory. It takes three
  1060. extra arguments:
  1061. ============== ========== ===============================================
  1062. Argument Required? Description
  1063. ============== ========== ===============================================
  1064. ``path`` Yes The absolute path to the directory whose
  1065. contents you want listed. This directory must
  1066. exist.
  1067. ``recursive`` No If ``False`` (the default) only the direct
  1068. contents of ``path`` will be offered as choices.
  1069. If ``True``, the directory will be descended
  1070. into recursively and all descendants will be
  1071. listed as choices.
  1072. ``match`` No A regular expression pattern; only files with
  1073. names matching this expression will be allowed
  1074. as choices.
  1075. ============== ========== ===============================================
  1076. ``FloatField``
  1077. ~~~~~~~~~~~~~~
  1078. * Default widget: ``TextInput``
  1079. * Empty value: ``None``
  1080. * Normalizes to: A Python float.
  1081. * Validates that the given value is an float. Leading and trailing
  1082. whitespace is allowed, as in Python's ``float()`` function.
  1083. * Error message keys: ``required``, ``invalid``, ``max_value``,
  1084. ``min_value``
  1085. Takes two optional arguments for validation, ``max_value`` and ``min_value``.
  1086. These control the range of values permitted in the field.
  1087. ``ImageField``
  1088. ~~~~~~~~~~~~~~
  1089. **New in Django development version**
  1090. * Default widget: ``FileInput``
  1091. * Empty value: ``None``
  1092. * Normalizes to: An ``UploadedFile`` object that wraps the file content
  1093. and file name into a single object.
  1094. * Validates that file data has been bound to the form, and that the
  1095. file is of an image format understood by PIL.
  1096. * Error message keys: ``required``, ``invalid``, ``missing``, ``empty``,
  1097. ``invalid_image``
  1098. Using an ImageField requires that the `Python Imaging Library`_ is installed.
  1099. When you use an ``ImageField`` in a form, you must also remember to
  1100. `bind the file data to the form`_.
  1101. .. _Python Imaging Library: http://www.pythonware.com/products/pil/
  1102. ``IntegerField``
  1103. ~~~~~~~~~~~~~~~~
  1104. * Default widget: ``TextInput``
  1105. * Empty value: ``None``
  1106. * Normalizes to: A Python integer or long integer.
  1107. * Validates that the given value is an integer. Leading and trailing
  1108. whitespace is allowed, as in Python's ``int()`` function.
  1109. * Error message keys: ``required``, ``invalid``, ``max_value``,
  1110. ``min_value``
  1111. Takes two optional arguments for validation, ``max_value`` and ``min_value``.
  1112. These control the range of values permitted in the field.
  1113. ``IPAddressField``
  1114. ~~~~~~~~~~~~~~~~~~
  1115. * Default widget: ``TextInput``
  1116. * Empty value: ``''`` (an empty string)
  1117. * Normalizes to: A Unicode object.
  1118. * Validates that the given value is a valid IPv4 address, using a regular
  1119. expression.
  1120. * Error message keys: ``required``, ``invalid``
  1121. ``MultipleChoiceField``
  1122. ~~~~~~~~~~~~~~~~~~~~~~~
  1123. * Default widget: ``SelectMultiple``
  1124. * Empty value: ``[]`` (an empty list)
  1125. * Normalizes to: A list of Unicode objects.
  1126. * Validates that every value in the given list of values exists in the list
  1127. of choices.
  1128. * Error message keys: ``required``, ``invalid_choice``, ``invalid_list``
  1129. Takes one extra argument, ``choices``, which is an iterable (e.g., a list or
  1130. tuple) of 2-tuples to use as choices for this field. This argument accepts
  1131. the same formats as the ``choices`` argument to a model field. See the
  1132. `model API documentation on choices`_ for more details.
  1133. ``NullBooleanField``
  1134. ~~~~~~~~~~~~~~~~~~~~
  1135. * Default widget: ``NullBooleanSelect``
  1136. * Empty value: ``None``
  1137. * Normalizes to: A Python ``True``, ``False`` or ``None`` value.
  1138. * Validates nothing (i.e., it never raises a ``ValidationError``).
  1139. ``RegexField``
  1140. ~~~~~~~~~~~~~~
  1141. * Default widget: ``TextInput``
  1142. * Empty value: ``''`` (an empty string)
  1143. * Normalizes to: A Unicode object.
  1144. * Validates that the given value matches against a certain regular
  1145. expression.
  1146. * Error message keys: ``required``, ``invalid``
  1147. Takes one required argument, ``regex``, which is a regular expression specified
  1148. either as a string or a compiled regular expression object.
  1149. Also takes the following optional arguments:
  1150. ====================== =====================================================
  1151. Argument Description
  1152. ====================== =====================================================
  1153. ``max_length`` Ensures the string has at most this many characters.
  1154. ``min_length`` Ensures the string has at least this many characters.
  1155. ====================== =====================================================
  1156. The optional argument ``error_message`` is also accepted for backwards
  1157. compatibility. The preferred way to provide an error message is to use the
  1158. ``error_messages`` argument, passing a dictionary with ``'invalid'`` as a key
  1159. and the error message as the value.
  1160. ``TimeField``
  1161. ~~~~~~~~~~~~~
  1162. * Default widget: ``TextInput``
  1163. * Empty value: ``None``
  1164. * Normalizes to: A Python ``datetime.time`` object.
  1165. * Validates that the given value is either a ``datetime.time`` or string
  1166. formatted in a particular time format.
  1167. * Error message keys: ``required``, ``invalid``
  1168. Takes one optional argument, ``input_formats``, which is a list of formats used
  1169. to attempt to convert a string to a valid ``datetime.time`` object.
  1170. If no ``input_formats`` argument is provided, the default input formats are::
  1171. '%H:%M:%S', # '14:30:59'
  1172. '%H:%M', # '14:30'
  1173. ``URLField``
  1174. ~~~~~~~~~~~~
  1175. * Default widget: ``TextInput``
  1176. * Empty value: ``''`` (an empty string)
  1177. * Normalizes to: A Unicode object.
  1178. * Validates that the given value is a valid URL.
  1179. * Error message keys: ``required``, ``invalid``, ``invalid_link``
  1180. Takes the following optional arguments:
  1181. ======================== =====================================================
  1182. Argument Description
  1183. ======================== =====================================================
  1184. ``max_length`` Ensures the string has at most this many characters.
  1185. ``min_length`` Ensures the string has at least this many characters.
  1186. ``verify_exists`` If ``True``, the validator will attempt to load the
  1187. given URL, raising ``ValidationError`` if the page
  1188. gives a 404. Defaults to ``False``.
  1189. ``validator_user_agent`` String used as the user-agent used when checking for
  1190. a URL's existence. Defaults to the value of the
  1191. ``URL_VALIDATOR_USER_AGENT`` setting.
  1192. ======================== =====================================================
  1193. Slightly complex built-in ``Field`` classes
  1194. -------------------------------------------
  1195. The following are not yet documented here. See the unit tests, linked-to from
  1196. the bottom of this document, for examples of their use.
  1197. ``ComboField``
  1198. ~~~~~~~~~~~~~~
  1199. ``MultiValueField``
  1200. ~~~~~~~~~~~~~~~~~~~
  1201. ``SplitDateTimeField``
  1202. ~~~~~~~~~~~~~~~~~~~~~~
  1203. Fields which handle relationships
  1204. ---------------------------------
  1205. For representing relationships between models, two fields are
  1206. provided which can derive their choices from a ``QuerySet``, and which
  1207. place one or more model objects into the ``cleaned_data`` dictionary
  1208. of forms in which they're used. Both of these fields have an
  1209. additional required argument:
  1210. ``queryset``
  1211. A ``QuerySet`` of model objects from which the choices for the
  1212. field will be derived, and which will be used to validate the
  1213. user's selection.
  1214. ``ModelChoiceField``
  1215. ~~~~~~~~~~~~~~~~~~~~
  1216. Allows the selection of a single model object, suitable for
  1217. representing a foreign key.
  1218. The ``__unicode__`` method of the model will be called to generate
  1219. string representations of the objects for use in the field's choices;
  1220. to provide customized representations, subclass ``ModelChoiceField``
  1221. and override ``label_from_instance``. This method will receive a model
  1222. object, and should return a string suitable for representing it. For
  1223. example::
  1224. class MyModelChoiceField(ModelChoiceField):
  1225. def label_from_instance(self, obj):
  1226. return "My Object #%i" % obj.id
  1227. ``ModelMultipleChoiceField``
  1228. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1229. Allows the selection of one or more model objects, suitable for
  1230. representing a many-to-many relation. As with ``ModelChoiceField``,
  1231. you can use ``label_from_instance`` to customize the object
  1232. representations.
  1233. Creating custom fields
  1234. ----------------------
  1235. If the built-in ``Field`` classes don't meet your needs, you can easily create
  1236. custom ``Field`` classes. To do this, just create a subclass of
  1237. ``django.forms.Field``. Its only requirements are that it implement a
  1238. ``clean()`` method and that its ``__init__()`` method accept the core arguments
  1239. mentioned above (``required``, ``label``, ``initial``, ``widget``,
  1240. ``help_text``).
  1241. Custom form and field validation
  1242. ---------------------------------
  1243. Form validation happens when the data is cleaned. If you want to customize
  1244. this process, there are various places you can change, each one serving a
  1245. different purpose. Three types of cleaning methods are run during form
  1246. processing. These are normally executed when you call the ``is_valid()``
  1247. method on a form. There are other things that can trigger cleaning and
  1248. validation (accessing the ``errors`` attribute or calling ``full_clean()``
  1249. directly), but normally they won't be needed.
  1250. In general, any cleaning method can raise ``ValidationError`` if there is a
  1251. problem with the data it is processing, passing the relevant error message to
  1252. the ``ValidationError`` constructor. If no ``ValidationError`` is raised, the
  1253. method should return the cleaned (normalized) data as a Python object.
  1254. If you detect multiple errors during a cleaning method and wish to signal all
  1255. of them to the form submitter, it is possible to pass a list of errors to the
  1256. ``ValidationError`` constructor.
  1257. The three types of cleaning methods are:
  1258. * The ``clean()`` method on a Field subclass. This is responsible
  1259. for cleaning the data in a way that is generic for that type of field.
  1260. For example, a FloatField will turn the data into a Python ``float`` or
  1261. raise a ``ValidationError``.
  1262. * The ``clean_<fieldname>()`` method in a form subclass -- where
  1263. ``<fieldname>`` is replaced with the name of the form field attribute.
  1264. This method does any cleaning that is specific to that particular
  1265. attribute, unrelated to the type of field that it is. This method is not
  1266. passed any parameters. You will need to look up the value of the field
  1267. in ``self.cleaned_data`` and remember that it will be a Python object
  1268. at this point, not the original string submitted in the form (it will be
  1269. in ``cleaned_data`` because the general field ``clean()`` method, above,
  1270. has already cleaned the data once).
  1271. For example, if you wanted to validate that the contents of a
  1272. ``CharField`` called ``serialnumber`` was unique,
  1273. ``clean_serialnumber()`` would be the right place to do this. You don't
  1274. need a specific field (it's just a ``CharField``), but you want a
  1275. formfield-specific piece of validation and, possibly,
  1276. cleaning/normalizing the data.
  1277. * The Form subclass's ``clean()`` method. This method can perform
  1278. any validation that requires access to multiple fields from the form at
  1279. once. This is where you might put in things to check that if field ``A``
  1280. is supplied, field ``B`` must contain a valid e-mail address and the
  1281. like. The data that this method returns is the final ``cleaned_data``
  1282. attribute for the form, so don't forget to return the full list of
  1283. cleaned data if you override this method (by default, ``Form.clean()``
  1284. just returns ``self.cleaned_data``).
  1285. Note that any errors raised by your ``Form.clean()`` override will not
  1286. be associated with any field in particular. They go into a special
  1287. "field" (called ``__all__``), which you can access via the
  1288. ``non_field_errors()`` method if you need to.
  1289. These methods are run in the order given above, one field at a time. That is,
  1290. for each field in the form (in the order they are declared in the form
  1291. definition), the ``Field.clean()`` method (or its override) is run, then
  1292. ``clean_<fieldname>()``. Finally, once those two methods are run for every
  1293. field, the ``Form.clean()`` method, or its override, is executed.
  1294. As mentioned above, any of these methods can raise a ``ValidationError``. For
  1295. any field, if the ``Field.clean()`` method raises a ``ValidationError``, any
  1296. field-specific cleaning method is not called. However, the cleaning methods
  1297. for all remaining fields are still executed.
  1298. The ``clean()`` method for the ``Form`` class or subclass is always run. If
  1299. that method raises a ``ValidationError``, ``cleaned_data`` will be an empty
  1300. dictionary.
  1301. The previous paragraph means that if you are overriding ``Form.clean()``, you
  1302. should iterate through ``self.cleaned_data.items()``, possibly considering the
  1303. ``_errors`` dictionary attribute on the form as well. In this way, you will
  1304. already know which fields have passed their individual validation requirements.
  1305. A simple example
  1306. ~~~~~~~~~~~~~~~~
  1307. Here's a simple example of a custom field that validates its input is a string
  1308. containing comma-separated e-mail addresses, with at least one address. We'll
  1309. keep it simple and assume e-mail validation is contained in a function called
  1310. ``is_valid_email()``. The full class::
  1311. from django import forms
  1312. class MultiEmailField(forms.Field):
  1313. def clean(self, value):
  1314. if not value:
  1315. raise forms.ValidationError('Enter at least one e-mail address.')
  1316. emails = value.split(',')
  1317. for email in emails:
  1318. if not is_valid_email(email):
  1319. raise forms.ValidationError('%s is not a valid e-mail address.' % email)
  1320. return emails
  1321. Let's alter the ongoing ``ContactForm`` example to demonstrate how you'd use
  1322. this in a form. Simply use ``MultiEmailField`` instead of ``forms.EmailField``,
  1323. like so::
  1324. class ContactForm(forms.Form):
  1325. subject = forms.CharField(max_length=100)
  1326. message = forms.CharField()
  1327. senders = MultiEmailField()
  1328. cc_myself = forms.BooleanField(required=False)
  1329. Widgets
  1330. =======
  1331. A widget is Django's representation of a HTML input element. The widget
  1332. handles the rendering of the HTML, and the extraction of data from a GET/POST
  1333. dictionary that corresponds to the widget.
  1334. Django provides a representation of all the basic HTML widgets, plus some
  1335. commonly used groups of widgets:
  1336. ============================ ===========================================
  1337. Widget HTML Equivalent
  1338. ============================ ===========================================
  1339. ``TextInput`` ``<input type='text' ...``
  1340. ``PasswordInput`` ``<input type='password' ...``
  1341. ``HiddenInput`` ``<input type='hidden' ...``
  1342. ``MultipleHiddenInput`` Multiple ``<input type='hidden' ...``
  1343. instances.
  1344. ``FileInput`` ``<input type='file' ...``
  1345. ``DateTimeInput`` ``<input type='text' ...``
  1346. ``Textarea`` ``<textarea>...</textarea>``
  1347. ``CheckboxInput`` ``<input type='checkbox' ...``
  1348. ``Select`` ``<select><option ...``
  1349. ``NullBooleanSelect`` Select widget with options 'Unknown',
  1350. 'Yes' and 'No'
  1351. ``SelectMultiple`` ``<select multiple='multiple'><option ...``
  1352. ``RadioSelect`` ``<ul><li><input type='radio' ...``
  1353. ``CheckboxSelectMultiple`` ``<ul><li><input type='checkbox' ...``
  1354. ``MultiWidget`` Wrapper around multiple other widgets
  1355. ``SplitDateTimeWidget`` Wrapper around two ``TextInput`` widgets:
  1356. one for the Date, and one for the Time.
  1357. ============================ ===========================================
  1358. **New in Django development version:** The ``DateTimeInput`` has been added
  1359. since the last release.
  1360. Specifying widgets
  1361. ------------------
  1362. Whenever you specify a field on a form, Django will use a default widget
  1363. that is appropriate to the type of data that is to be displayed. To find
  1364. which widget is used on which field, see the documentation for the
  1365. built-in Field classes.
  1366. However, if you want to use a different widget for a field, you can -
  1367. just use the 'widget' argument on the field definition. For example::
  1368. class CommentForm(forms.Form):
  1369. name = forms.CharField()
  1370. url = forms.URLField()
  1371. comment = forms.CharField(widget=forms.Textarea)
  1372. This would specify a form with a comment that uses a larger Textarea widget,
  1373. rather than the default TextInput widget.
  1374. Customizing widget instances
  1375. ----------------------------
  1376. When Django renders a widget as HTML, it only renders the bare minimum
  1377. HTML - Django doesn't add a class definition, or any other widget-specific
  1378. attributes. This means that all 'TextInput' widgets will appear the same
  1379. on your Web page.
  1380. If you want to make one widget look different to another, you need to
  1381. specify additional attributes for each widget. When you specify a
  1382. widget, you can provide a list of attributes that will be added to the
  1383. rendered HTML for the widget.
  1384. For example, take the following simple form::
  1385. class CommentForm(forms.Form):
  1386. name = forms.CharField()
  1387. url = forms.URLField()
  1388. comment = forms.CharField()
  1389. This form will include three default TextInput widgets, with default rendering -
  1390. no CSS class, no extra attributes. This means that the input boxes provided for
  1391. each widget will be rendered exactly the same::
  1392. >>> f = CommentForm(auto_id=False)
  1393. >>> f.as_table()
  1394. <tr><th>Name:</th><td><input type="text" name="name" /></td></tr>
  1395. <tr><th>Url:</th><td><input type="text" name="url"/></td></tr>
  1396. <tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr>
  1397. On a real Web page, you probably don't want every widget to look the same. You
  1398. might want a larger input element for the comment, and you might want the
  1399. 'name' widget to have some special CSS class. To do this, you specify a
  1400. custom widget for your fields, and specify some attributes to use
  1401. when rendering those widgets::
  1402. class CommentForm(forms.Form):
  1403. name = forms.CharField(
  1404. widget=forms.TextInput(attrs={'class':'special'}))
  1405. url = forms.URLField()
  1406. comment = forms.CharField(
  1407. widget=forms.TextInput(attrs={'size':'40'}))
  1408. Django will then include the extra attributes in the rendered output::
  1409. >>> f = CommentForm(auto_id=False)
  1410. >>> f.as_table()
  1411. <tr><th>Name:</th><td><input type="text" name="name" class="special"/></td></tr>
  1412. <tr><th>Url:</th><td><input type="text" name="url"/></td></tr>
  1413. <tr><th>Comment:</th><td><input type="text" name="comment" size="40"/></td></tr>
  1414. Custom Widgets
  1415. --------------
  1416. When you start to write a lot of forms, you will probably find that you will
  1417. reuse certain sets of widget attributes over and over again. Rather than
  1418. repeat these attribute definitions every time you need them, Django allows
  1419. you to capture those definitions as a custom widget.
  1420. For example, if you find that you are including a lot of comment fields on
  1421. forms, you could capture the idea of a ``TextInput`` with a specific
  1422. default ``size`` attribute as a custom extension to the ``TextInput`` widget::
  1423. class CommentWidget(forms.TextInput):
  1424. def __init__(self, *args, **kwargs):
  1425. attrs = kwargs.setdefault('attrs',{})
  1426. if 'size' not in attrs:
  1427. attrs['size'] = 40
  1428. super(CommentWidget, self).__init__(*args, **kwargs)
  1429. We allow the ``size`` attribute to be overridden by the user, but, by default,
  1430. this widget will behave as if ``attrs={'size': 40}`` was always passed into the
  1431. constructor.
  1432. Then you can use this widget in your forms::
  1433. class CommentForm(forms.Form):
  1434. name = forms.CharField()
  1435. url = forms.URLField()
  1436. comment = forms.CharField(widget=CommentWidget)
  1437. You can even customize your custom widget, in the same way as you would
  1438. any other widget. Adding a once-off class to your ``CommentWidget`` is as
  1439. simple as adding an attribute definition::
  1440. class CommentForm(forms.Form):
  1441. name = forms.CharField(max_length=20)
  1442. url = forms.URLField()
  1443. comment = forms.CharField(
  1444. widget=CommentWidget(attrs={'class': 'special'}))
  1445. Django also makes it easy to specify a custom field type that uses your custom
  1446. widget. For example, you could define a customized field type for comments
  1447. by defining::
  1448. class CommentInput(forms.CharField):
  1449. widget = CommentWidget
  1450. You can then use this field whenever you have a form that requires a comment::
  1451. class CommentForm(forms.Form):
  1452. name = forms.CharField()
  1453. url = forms.URLField()
  1454. comment = CommentInput()
  1455. Generating forms for models
  1456. ===========================
  1457. The prefered way of generating forms that work with models is explained in the
  1458. `ModelForms documentation`_.
  1459. .. _ModelForms documentation: ../modelforms/
  1460. Media
  1461. =====
  1462. Rendering an attractive and easy-to-use web form requires more than just
  1463. HTML - it also requires CSS stylesheets, and if you want to use fancy
  1464. "Web2.0" widgets, you may also need to include some JavaScript on each
  1465. page. The exact combination of CSS and JavaScript that is required for
  1466. any given page will depend upon the widgets that are in use on that page.
  1467. This is where Django media definitions come in. Django allows you to
  1468. associate different media files with the forms and widgets that require
  1469. that media. For example, if you want to use a calendar to render DateFields,
  1470. you can define a custom Calendar widget. This widget can then be associated
  1471. with the CSS and JavaScript that is required to render the calendar. When
  1472. the Calendar widget is used on a form, Django is able to identify the CSS and
  1473. JavaScript files that are required, and provide the list of file names
  1474. in a form suitable for easy inclusion on your web page.
  1475. .. admonition:: Media and Django Admin
  1476. The Django Admin application defines a number of customized widgets
  1477. for calendars, filtered selections, and so on. These widgets define
  1478. media requirements, and the Django Admin uses the custom widgets
  1479. in place of the Django defaults. The Admin templates will only include
  1480. those media files that are required to render the widgets on any
  1481. given page.
  1482. If you like the widgets that the Django Admin application uses,
  1483. feel free to use them in your own application! They're all stored
  1484. in ``django.contrib.admin.widgets``.
  1485. .. admonition:: Which JavaScript toolkit?
  1486. Many JavaScript toolkits exist, and many of them include widgets (such
  1487. as calendar widgets) that can be used to enhance your application.
  1488. Django has deliberately avoided blessing any one JavaScript toolkit.
  1489. Each toolkit has its own relative strengths and weaknesses - use
  1490. whichever toolkit suits your requirements. Django is able to integrate
  1491. with any JavaScript toolkit.
  1492. Media as a static definition
  1493. ----------------------------
  1494. The easiest way to define media is as a static definition. Using this method,
  1495. the media declaration is an inner class. The properties of the inner class
  1496. define the media requirements.
  1497. Here's a simple example::
  1498. class CalendarWidget(forms.TextInput):
  1499. class Media:
  1500. css = {
  1501. 'all': ('pretty.css',)
  1502. }
  1503. js = ('animations.js', 'actions.js')
  1504. This code defines a ``CalendarWidget``, which will be based on ``TextInput``.
  1505. Every time the CalendarWidget is used on a form, that form will be directed
  1506. to include the CSS file ``pretty.css``, and the JavaScript files
  1507. ``animations.js`` and ``actions.js``.
  1508. This static media definition is converted at runtime into a widget property
  1509. named ``media``. The media for a CalendarWidget instance can be retrieved
  1510. through this property::
  1511. >>> w = CalendarWidget()
  1512. >>> print w.media
  1513. <link href="http://media.example.com/pretty.css" type="text/css" media="all" rel="stylesheet" />
  1514. <script type="text/javascript" src="http://media.example.com/animations.js"></script>
  1515. <script type="text/javascript" src="http://media.example.com/actions.js"></script>
  1516. Here's a list of all possible ``Media`` options. There are no required options.
  1517. ``css``
  1518. ~~~~~~~
  1519. A dictionary describing the CSS files required for various forms of output
  1520. media.
  1521. The values in the dictionary should be a tuple/list of file names. See
  1522. `the section on media paths`_ for details of how to specify paths to media
  1523. files.
  1524. .. _the section on media paths: `Paths in media definitions`_
  1525. The keys in the dictionary are the output media types. These are the same
  1526. types accepted by CSS files in media declarations: 'all', 'aural', 'braille',
  1527. 'embossed', 'handheld', 'print', 'projection', 'screen', 'tty' and 'tv'. If
  1528. you need to have different stylesheets for different media types, provide
  1529. a list of CSS files for each output medium. The following example would
  1530. provide two CSS options -- one for the screen, and one for print::
  1531. class Media:
  1532. css = {
  1533. 'screen': ('pretty.css',),
  1534. 'print': ('newspaper.css',)
  1535. }
  1536. If a group of CSS files are appropriate for multiple output media types,
  1537. the dictionary key can be a comma separated list of output media types.
  1538. In the following example, TV's and projectors will have the same media
  1539. requirements::
  1540. class Media:
  1541. css = {
  1542. 'screen': ('pretty.css',),
  1543. 'tv,projector': ('lo_res.css',),
  1544. 'print': ('newspaper.css',)
  1545. }
  1546. If this last CSS definition were to be rendered, it would become the following HTML::
  1547. <link href="http://media.example.com/pretty.css" type="text/css" media="screen" rel="stylesheet" />
  1548. <link href="http://media.example.com/lo_res.css" type="text/css" media="tv,projector" rel="stylesheet" />
  1549. <link href="http://media.example.com/newspaper.css" type="text/css" media="print" rel="stylesheet" />
  1550. ``js``
  1551. ~~~~~~
  1552. A tuple describing the required JavaScript files. See
  1553. `the section on media paths`_ for details of how to specify paths to media
  1554. files.
  1555. ``extend``
  1556. ~~~~~~~~~~
  1557. A boolean defining inheritance behavior for media declarations.
  1558. By default, any object using a static media definition will inherit all the
  1559. media associated with the parent widget. This occurs regardless of how the
  1560. parent defines its media requirements. For example, if we were to extend our
  1561. basic Calendar widget from the example above::
  1562. class FancyCalendarWidget(CalendarWidget):
  1563. class Media:
  1564. css = {
  1565. 'all': ('fancy.css',)
  1566. }
  1567. js = ('whizbang.js',)
  1568. >>> w = FancyCalendarWidget()
  1569. >>> print w.media
  1570. <link href="http://media.example.com/pretty.css" type="text/css" media="all" rel="stylesheet" />
  1571. <link href="http://media.example.com/fancy.css" type="text/css" media="all" rel="stylesheet" />
  1572. <script type="text/javascript" src="http://media.example.com/animations.js"></script>
  1573. <script type="text/javascript" src="http://media.example.com/actions.js"></script>
  1574. <script type="text/javascript" src="http://media.example.com/whizbang.js"></script>
  1575. The FancyCalendar widget inherits all the media from it's parent widget. If
  1576. you don't want media to be inherited in this way, add an ``extend=False``
  1577. declaration to the media declaration::
  1578. class FancyCalendar(Calendar):
  1579. class Media:
  1580. extend = False
  1581. css = {
  1582. 'all': ('fancy.css',)
  1583. }
  1584. js = ('whizbang.js',)
  1585. >>> w = FancyCalendarWidget()
  1586. >>> print w.media
  1587. <link href="http://media.example.com/fancy.css" type="text/css" media="all" rel="stylesheet" />
  1588. <script type="text/javascript" src="http://media.example.com/whizbang.js"></script>
  1589. If you require even more control over media inheritance, define your media
  1590. using a `dynamic property`_. Dynamic properties give you complete control over
  1591. which media files are inherited, and which are not.
  1592. .. _dynamic property: `Media as a dynamic property`_
  1593. Media as a dynamic property
  1594. ---------------------------
  1595. If you need to perform some more sophisticated manipulation of media
  1596. requirements, you can define the media property directly. This is done
  1597. by defining a model property that returns an instance of ``forms.Media``.
  1598. The constructor for ``forms.Media`` accepts ``css`` and ``js`` keyword
  1599. arguments in the same format as that used in a static media definition.
  1600. For example, the static media definition for our Calendar Widget could
  1601. also be defined in a dynamic fashion::
  1602. class CalendarWidget(forms.TextInput):
  1603. def _media(self):
  1604. return forms.Media(css={'all': ('pretty.css',)},
  1605. js=('animations.js', 'actions.js'))
  1606. media = property(_media)
  1607. See the section on `Media objects`_ for more details on how to construct
  1608. return values for dynamic media properties.
  1609. Paths in media definitions
  1610. --------------------------
  1611. Paths used to specify media can be either relative or absolute. If a path
  1612. starts with '/', 'http://' or 'https://', it will be interpreted as an absolute
  1613. path, and left as-is. All other paths will be prepended with the value of
  1614. ``settings.MEDIA_URL``. For example, if the MEDIA_URL for your site was
  1615. ``http://media.example.com/``::
  1616. class CalendarWidget(forms.TextInput):
  1617. class Media:
  1618. css = {
  1619. 'all': ('/css/pretty.css',),
  1620. }
  1621. js = ('animations.js', 'http://othersite.com/actions.js')
  1622. >>> w = CalendarWidget()
  1623. >>> print w.media
  1624. <link href="/css/pretty.css" type="text/css" media="all" rel="stylesheet" />
  1625. <script type="text/javascript" src="http://media.example.com/animations.js"></script>
  1626. <script type="text/javascript" src="http://othersite.com/actions.js"></script>
  1627. Media objects
  1628. -------------
  1629. When you interrogate the media attribute of a widget or form, the value that
  1630. is returned is a ``forms.Media`` object. As we have already seen, the string
  1631. representation of a Media object is the HTML required to include media
  1632. in the ``<head>`` block of your HTML page.
  1633. However, Media objects have some other interesting properties.
  1634. Media subsets
  1635. ~~~~~~~~~~~~~
  1636. If you only want media of a particular type, you can use the subscript operator
  1637. to filter out a medium of interest. For example::
  1638. >>> w = CalendarWidget()
  1639. >>> print w.media
  1640. <link href="http://media.example.com/pretty.css" type="text/css" media="all" rel="stylesheet" />
  1641. <script type="text/javascript" src="http://media.example.com/animations.js"></script>
  1642. <script type="text/javascript" src="http://media.example.com/actions.js"></script>
  1643. >>> print w.media['css']
  1644. <link href="http://media.example.com/pretty.css" type="text/css" media="all" rel="stylesheet" />
  1645. When you use the subscript operator, the value that is returned is a new
  1646. Media object -- but one that only contains the media of interest.
  1647. Combining media objects
  1648. ~~~~~~~~~~~~~~~~~~~~~~~
  1649. Media objects can also be added together. When two media objects are added,
  1650. the resulting Media object contains the union of the media from both files::
  1651. class CalendarWidget(forms.TextInput):
  1652. class Media:
  1653. css = {
  1654. 'all': ('pretty.css',)
  1655. }
  1656. js = ('animations.js', 'actions.js')
  1657. class OtherWidget(forms.TextInput):
  1658. class Media:
  1659. js = ('whizbang.js',)
  1660. >>> w1 = CalendarWidget()
  1661. >>> w2 = OtherWidget()
  1662. >>> print w1.media + w2.media
  1663. <link href="http://media.example.com/pretty.css" type="text/css" media="all" rel="stylesheet" />
  1664. <script type="text/javascript" src="http://media.example.com/animations.js"></script>
  1665. <script type="text/javascript" src="http://media.example.com/actions.js"></script>
  1666. <script type="text/javascript" src="http://media.example.com/whizbang.js"></script>
  1667. Media on Forms
  1668. --------------
  1669. Widgets aren't the only objects that can have media definitions -- forms
  1670. can also define media. The rules for media definitions on forms are the
  1671. same as the rules for widgets: declarations can be static or dynamic;
  1672. path and inheritance rules for those declarations are exactly the same.
  1673. Regardless of whether you define a media declaration, *all* Form objects
  1674. have a media property. The default value for this property is the result
  1675. of adding the media definitions for all widgets that are part of the form::
  1676. class ContactForm(forms.Form):
  1677. date = DateField(widget=CalendarWidget)
  1678. name = CharField(max_length=40, widget=OtherWidget)
  1679. >>> f = ContactForm()
  1680. >>> f.media
  1681. <link href="http://media.example.com/pretty.css" type="text/css" media="all" rel="stylesheet" />
  1682. <script type="text/javascript" src="http://media.example.com/animations.js"></script>
  1683. <script type="text/javascript" src="http://media.example.com/actions.js"></script>
  1684. <script type="text/javascript" src="http://media.example.com/whizbang.js"></script>
  1685. If you want to associate additional media with a form -- for example, CSS for form
  1686. layout -- simply add a media declaration to the form::
  1687. class ContactForm(forms.Form):
  1688. date = DateField(widget=CalendarWidget)
  1689. name = CharField(max_length=40, widget=OtherWidget)
  1690. class Media:
  1691. css = {
  1692. 'all': ('layout.css',)
  1693. }
  1694. >>> f = ContactForm()
  1695. >>> f.media
  1696. <link href="http://media.example.com/pretty.css" type="text/css" media="all" rel="stylesheet" />
  1697. <link href="http://media.example.com/layout.css" type="text/css" media="all" rel="stylesheet" />
  1698. <script type="text/javascript" src="http://media.example.com/animations.js"></script>
  1699. <script type="text/javascript" src="http://media.example.com/actions.js"></script>
  1700. <script type="text/javascript" src="http://media.example.com/whizbang.js"></script>
  1701. Formsets
  1702. ========
  1703. A formset is a layer of abstraction to working with multiple forms on the same
  1704. page. It can be best compared to a data grid. Let's say you have the following
  1705. form::
  1706. >>> from django import forms
  1707. >>> class ArticleForm(forms.Form):
  1708. ... title = forms.CharField()
  1709. ... pub_date = forms.DateField()
  1710. You might want to allow the user to create several articles at once. To create
  1711. a formset out of an ``ArticleForm`` you would do::
  1712. >>> from django.forms.formsets import formset_factory
  1713. >>> ArticleFormSet = formset_factory(ArticleForm)
  1714. You now have created a formset named ``ArticleFormSet``. The formset gives you
  1715. the ability to iterate over the forms in the formset and display them as you
  1716. would with a regular form::
  1717. >>> formset = ArticleFormSet()
  1718. >>> for form in formset.forms:
  1719. ... print form.as_table()
  1720. <tr><th><label for="id_form-0-title">Title:</label></th><td><input type="text" name="form-0-title" id="id_form-0-title" /></td></tr>
  1721. <tr><th><label for="id_form-0-pub_date">Pub date:</label></th><td><input type="text" name="form-0-pub_date" id="id_form-0-pub_date" /></td></tr>
  1722. As you can see it only displayed one form. This is because by default the
  1723. ``formset_factory`` defines one extra form. This can be controlled with the
  1724. ``extra`` parameter::
  1725. >>> ArticleFormSet = formset_factory(ArticleForm, extra=2)
  1726. Using initial data with a formset
  1727. ---------------------------------
  1728. Initial data is what drives the main usability of a formset. As shown above
  1729. you can define the number of extra forms. What this means is that you are
  1730. telling the formset how many additional forms to show in addition to the
  1731. number of forms it generates from the initial data. Lets take a look at an
  1732. example::
  1733. >>> ArticleFormSet = formset_factory(ArticleForm, extra=2)
  1734. >>> formset = ArticleFormSet(initial=[
  1735. ... {'title': u'Django is now open source',
  1736. ... 'pub_date': datetime.date.today()},
  1737. ... ])
  1738. >>> for form in formset.forms:
  1739. ... print form.as_table()
  1740. <tr><th><label for="id_form-0-title">Title:</label></th><td><input type="text" name="form-0-title" value="Django is now open source" id="id_form-0-title" /></td></tr>
  1741. <tr><th><label for="id_form-0-pub_date">Pub date:</label></th><td><input type="text" name="form-0-pub_date" value="2008-05-12" id="id_form-0-pub_date" /></td></tr>
  1742. <tr><th><label for="id_form-1-title">Title:</label></th><td><input type="text" name="form-1-title" id="id_form-1-title" /></td></tr>
  1743. <tr><th><label for="id_form-1-pub_date">Pub date:</label></th><td><input type="text" name="form-1-pub_date" id="id_form-1-pub_date" /></td></tr>
  1744. <tr><th><label for="id_form-2-title">Title:</label></th><td><input type="text" name="form-2-title" id="id_form-2-title" /></td></tr>
  1745. <tr><th><label for="id_form-2-pub_date">Pub date:</label></th><td><input type="text" name="form-2-pub_date" id="id_form-2-pub_date" /></td></tr>
  1746. There are now a total of three forms showing above. One for the initial data
  1747. that was passed in and two extra forms. Also note that we are passing in a
  1748. list of dictionaries as the initial data.
  1749. Limiting the maximum number of forms
  1750. ------------------------------------
  1751. The ``max_num`` parameter to ``formset_factory`` gives you the ability to
  1752. force the maximum number of forms the formset will display::
  1753. >>> ArticleFormSet = formset_factory(ArticleForm, extra=2, max_num=1)
  1754. >>> formset = ArticleFormset()
  1755. >>> for form in formset.forms:
  1756. ... print form.as_table()
  1757. <tr><th><label for="id_form-0-title">Title:</label></th><td><input type="text" name="form-0-title" id="id_form-0-title" /></td></tr>
  1758. <tr><th><label for="id_form-0-pub_date">Pub date:</label></th><td><input type="text" name="form-0-pub_date" id="id_form-0-pub_date" /></td></tr>
  1759. The default value of ``max_num`` is ``0`` which is the same as saying put no
  1760. limit on the number forms displayed.
  1761. Formset validation
  1762. ------------------
  1763. Validation with a formset is about identical to a regular ``Form``. There is
  1764. an ``is_valid`` method on the formset to provide a convenient way to validate
  1765. each form in the formset::
  1766. >>> ArticleFormSet = formset_factory(ArticleForm)
  1767. >>> formset = ArticleFormSet({})
  1768. >>> formset.is_valid()
  1769. True
  1770. We passed in no data to the formset which is resulting in a valid form. The
  1771. formset is smart enough to ignore extra forms that were not changed. If we
  1772. attempt to provide an article, but fail to do so::
  1773. >>> data = {
  1774. ... 'form-TOTAL_FORMS': u'1',
  1775. ... 'form-INITIAL_FORMS': u'1',
  1776. ... 'form-0-title': u'Test',
  1777. ... 'form-0-pub_date': u'',
  1778. ... }
  1779. >>> formset = ArticleFormSet(data)
  1780. >>> formset.is_valid()
  1781. False
  1782. >>> formset.errors
  1783. [{'pub_date': [u'This field is required.']}]
  1784. As we can see the formset properly performed validation and gave us the
  1785. expected errors.
  1786. Understanding the ManagementForm
  1787. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1788. You may have noticed the additional data that was required in the formset's
  1789. data above. This data is coming from the ``ManagementForm``. This form is
  1790. dealt with internally to the formset. If you don't use it, it will result in
  1791. an exception::
  1792. >>> data = {
  1793. ... 'form-0-title': u'Test',
  1794. ... 'form-0-pub_date': u'',
  1795. ... }
  1796. >>> formset = ArticleFormSet(data)
  1797. Traceback (most recent call last):
  1798. ...
  1799. django.forms.util.ValidationError: [u'ManagementForm data is missing or has been tampered with']
  1800. It is used to keep track of how many form instances are being displayed. If
  1801. you are adding new forms via JavaScript, you should increment the count fields
  1802. in this form as well.
  1803. Custom formset validation
  1804. ~~~~~~~~~~~~~~~~~~~~~~~~~
  1805. A formset has a ``clean`` method similar to the one on a ``Form`` class. This
  1806. is where you define your own validation that deals at the formset level::
  1807. >>> from django.forms.formsets import BaseFormSet
  1808. >>> class BaseArticleFormSet(BaseFormSet):
  1809. ... def clean(self):
  1810. ... raise forms.ValidationError, u'An error occured.'
  1811. >>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet)
  1812. >>> formset = ArticleFormSet({})
  1813. >>> formset.is_valid()
  1814. False
  1815. >>> formset.non_form_errors()
  1816. [u'An error occured.']
  1817. The formset ``clean`` method is called after all the ``Form.clean`` methods
  1818. have been called. The errors will be found using the ``non_form_errors()``
  1819. method on the formset.
  1820. Dealing with ordering and deletion of forms
  1821. -------------------------------------------
  1822. Common use cases with a formset is dealing with ordering and deletion of the
  1823. form instances. This has been dealt with for you. The ``formset_factory``
  1824. provides two optional parameters ``can_order`` and ``can_delete`` that will do
  1825. the extra work of adding the extra fields and providing simpler ways of
  1826. getting to that data.
  1827. ``can_order``
  1828. ~~~~~~~~~~~~~
  1829. Default: ``False``
  1830. Lets create a formset with the ability to order::
  1831. >>> ArticleFormSet = formset_factory(ArticleForm, can_order=True)
  1832. >>> formset = ArticleFormSet(initial=[
  1833. ... {'title': u'Article #1', 'pub_date': datetime.date(2008, 5, 10)},
  1834. ... {'title': u'Article #2', 'pub_date': datetime.date(2008, 5, 11)},
  1835. ... ])
  1836. >>> for form in formset.forms:
  1837. ... print form.as_table()
  1838. <tr><th><label for="id_form-0-title">Title:</label></th><td><input type="text" name="form-0-title" value="Article #1" id="id_form-0-title" /></td></tr>
  1839. <tr><th><label for="id_form-0-pub_date">Pub date:</label></th><td><input type="text" name="form-0-pub_date" value="2008-05-10" id="id_form-0-pub_date" /></td></tr>
  1840. <tr><th><label for="id_form-0-ORDER">Order:</label></th><td><input type="text" name="form-0-ORDER" value="1" id="id_form-0-ORDER" /></td></tr>
  1841. <tr><th><label for="id_form-1-title">Title:</label></th><td><input type="text" name="form-1-title" value="Article #2" id="id_form-1-title" /></td></tr>
  1842. <tr><th><label for="id_form-1-pub_date">Pub date:</label></th><td><input type="text" name="form-1-pub_date" value="2008-05-11" id="id_form-1-pub_date" /></td></tr>
  1843. <tr><th><label for="id_form-1-ORDER">Order:</label></th><td><input type="text" name="form-1-ORDER" value="2" id="id_form-1-ORDER" /></td></tr>
  1844. <tr><th><label for="id_form-2-title">Title:</label></th><td><input type="text" name="form-2-title" id="id_form-2-title" /></td></tr>
  1845. <tr><th><label for="id_form-2-pub_date">Pub date:</label></th><td><input type="text" name="form-2-pub_date" id="id_form-2-pub_date" /></td></tr>
  1846. <tr><th><label for="id_form-2-ORDER">Order:</label></th><td><input type="text" name="form-2-ORDER" id="id_form-2-ORDER" /></td></tr>
  1847. This adds an additional field to each form. This new field is named ``ORDER``
  1848. and is an ``forms.IntegerField``. For the forms that came from the initial
  1849. data it automatically assigned them a numeric value. Lets look at what will
  1850. happen when the user changes these values::
  1851. >>> data = {
  1852. ... 'form-TOTAL_FORMS': u'3',
  1853. ... 'form-INITIAL_FORMS': u'2',
  1854. ... 'form-0-title': u'Article #1',
  1855. ... 'form-0-pub_date': u'2008-05-10',
  1856. ... 'form-0-ORDER': u'2',
  1857. ... 'form-1-title': u'Article #2',
  1858. ... 'form-1-pub_date': u'2008-05-11',
  1859. ... 'form-1-ORDER': u'1',
  1860. ... 'form-2-title': u'Article #3',
  1861. ... 'form-2-pub_date': u'2008-05-01',
  1862. ... 'form-2-ORDER': u'0',
  1863. ... }
  1864. >>> formset = ArticleFormSet(data, initial=[
  1865. ... {'title': u'Article #1', 'pub_date': datetime.date(2008, 5, 10)},
  1866. ... {'title': u'Article #2', 'pub_date': datetime.date(2008, 5, 11)},
  1867. ... ])
  1868. >>> formset.is_valid()
  1869. True
  1870. >>> for form in formset.ordered_forms:
  1871. ... print form.cleaned_data
  1872. {'pub_date': datetime.date(2008, 5, 1), 'ORDER': 0, 'title': u'Article #3'}
  1873. {'pub_date': datetime.date(2008, 5, 11), 'ORDER': 1, 'title': u'Article #2'}
  1874. {'pub_date': datetime.date(2008, 5, 10), 'ORDER': 2, 'title': u'Article #1'}
  1875. ``can_delete``
  1876. ~~~~~~~~~~~~~~
  1877. Default: ``False``
  1878. Lets create a formset with the ability to delete::
  1879. >>> ArticleFormSet = formset_factory(ArticleForm, can_delete=True)
  1880. >>> formset = ArticleFormSet(initial=[
  1881. ... {'title': u'Article #1', 'pub_date': datetime.date(2008, 5, 10)},
  1882. ... {'title': u'Article #2', 'pub_date': datetime.date(2008, 5, 11)},
  1883. ... ])
  1884. >>> for form in formset.forms:
  1885. .... print form.as_table()
  1886. <input type="hidden" name="form-TOTAL_FORMS" value="3" id="id_form-TOTAL_FORMS" /><input type="hidden" name="form-INITIAL_FORMS" value="2" id="id_form-INITIAL_FORMS" />
  1887. <tr><th><label for="id_form-0-title">Title:</label></th><td><input type="text" name="form-0-title" value="Article #1" id="id_form-0-title" /></td></tr>
  1888. <tr><th><label for="id_form-0-pub_date">Pub date:</label></th><td><input type="text" name="form-0-pub_date" value="2008-05-10" id="id_form-0-pub_date" /></td></tr>
  1889. <tr><th><label for="id_form-0-DELETE">Delete:</label></th><td><input type="checkbox" name="form-0-DELETE" id="id_form-0-DELETE" /></td></tr>
  1890. <tr><th><label for="id_form-1-title">Title:</label></th><td><input type="text" name="form-1-title" value="Article #2" id="id_form-1-title" /></td></tr>
  1891. <tr><th><label for="id_form-1-pub_date">Pub date:</label></th><td><input type="text" name="form-1-pub_date" value="2008-05-11" id="id_form-1-pub_date" /></td></tr>
  1892. <tr><th><label for="id_form-1-DELETE">Delete:</label></th><td><input type="checkbox" name="form-1-DELETE" id="id_form-1-DELETE" /></td></tr>
  1893. <tr><th><label for="id_form-2-title">Title:</label></th><td><input type="text" name="form-2-title" id="id_form-2-title" /></td></tr>
  1894. <tr><th><label for="id_form-2-pub_date">Pub date:</label></th><td><input type="text" name="form-2-pub_date" id="id_form-2-pub_date" /></td></tr>
  1895. <tr><th><label for="id_form-2-DELETE">Delete:</label></th><td><input type="checkbox" name="form-2-DELETE" id="id_form-2-DELETE" /></td></tr>
  1896. Similar to ``can_order`` this adds a new field to each form named ``DELETE``
  1897. and is a ``forms.BooleanField``. When data comes through marking any of the
  1898. delete fields you can access them with ``deleted_forms``::
  1899. >>> data = {
  1900. ... 'form-TOTAL_FORMS': u'3',
  1901. ... 'form-INITIAL_FORMS': u'2',
  1902. ... 'form-0-title': u'Article #1',
  1903. ... 'form-0-pub_date': u'2008-05-10',
  1904. ... 'form-0-DELETE': u'on',
  1905. ... 'form-1-title': u'Article #2',
  1906. ... 'form-1-pub_date': u'2008-05-11',
  1907. ... 'form-1-DELETE': u'',
  1908. ... 'form-2-title': u'',
  1909. ... 'form-2-pub_date': u'',
  1910. ... 'form-2-DELETE': u'',
  1911. ... }
  1912. >>> formset = ArticleFormSet(data, initial=[
  1913. ... {'title': u'Article #1', 'pub_date': datetime.date(2008, 5, 10)},
  1914. ... {'title': u'Article #2', 'pub_date': datetime.date(2008, 5, 11)},
  1915. ... ])
  1916. >>> [form.cleaned_data for form in formset.deleted_forms]
  1917. [{'DELETE': True, 'pub_date': datetime.date(2008, 5, 10), 'title': u'Article #1'}]
  1918. Adding additional fields to a formset
  1919. -------------------------------------
  1920. If you need to add additional fields to the formset this can be easily
  1921. accomplished. The formset base class provides an ``add_fields`` method. You
  1922. can simply override this method to add your own fields or even redefine the
  1923. default fields/attributes of the order and deletion fields::
  1924. >>> class BaseArticleFormSet(BaseFormSet):
  1925. ... def add_fields(self, form, index):
  1926. ... super(BaseArticleFormSet, self).add_fields(form, index)
  1927. ... form.fields["my_field"] = forms.CharField()
  1928. >>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet)
  1929. >>> formset = ArticleFormSet()
  1930. >>> for form in formset.forms:
  1931. ... print form.as_table()
  1932. <tr><th><label for="id_form-0-title">Title:</label></th><td><input type="text" name="form-0-title" id="id_form-0-title" /></td></tr>
  1933. <tr><th><label for="id_form-0-pub_date">Pub date:</label></th><td><input type="text" name="form-0-pub_date" id="id_form-0-pub_date" /></td></tr>
  1934. <tr><th><label for="id_form-0-my_field">My field:</label></th><td><input type="text" name="form-0-my_field" id="id_form-0-my_field" /></td></tr>
  1935. Using a formset in views and templates
  1936. --------------------------------------
  1937. Using a formset inside a view is as easy as using a regular ``Form`` class.
  1938. The only thing you will want to be aware of is making sure to use the
  1939. management form inside the template. Lets look at a sample view::
  1940. def manage_articles(request):
  1941. ArticleFormSet = formset_factory(ArticleForm)
  1942. if request.method == 'POST':
  1943. formset = ArticleFormSet(request.POST, request.FILES)
  1944. if formset.is_valid():
  1945. # do something with the formset.cleaned_data
  1946. else:
  1947. formset = ArticleFormSet()
  1948. return render_to_response('manage_articles.html', {'formset': formset})
  1949. The ``manage_articles.html`` template might look like this::
  1950. <form method="POST" action="">
  1951. {{ formset.management_form }}
  1952. <table>
  1953. {% for form in formset.forms %}
  1954. {{ form }}
  1955. {% endfor %}
  1956. </table>
  1957. </form>
  1958. However the above can be slightly shortcutted and let the formset itself deal
  1959. with the management form::
  1960. <form method="POST" action="">
  1961. <table>
  1962. {{ formset }}
  1963. </table>
  1964. </form>
  1965. The above ends up calling the ``as_table`` method on the formset class.