fields.txt 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133
  1. ===========
  2. Form fields
  3. ===========
  4. .. module:: django.forms.fields
  5. :synopsis: Django's built-in form fields.
  6. .. currentmodule:: django.forms
  7. .. class:: Field(**kwargs)
  8. When you create a ``Form`` class, the most important part is defining the
  9. fields of the form. Each field has custom validation logic, along with a few
  10. other hooks.
  11. .. method:: Field.clean(value)
  12. Although the primary way you'll use ``Field`` classes is in ``Form`` classes,
  13. you can also instantiate them and use them directly to get a better idea of
  14. how they work. Each ``Field`` instance has a ``clean()`` method, which takes
  15. a single argument and either raises a ``django.forms.ValidationError``
  16. exception or returns the clean value::
  17. >>> from django import forms
  18. >>> f = forms.EmailField()
  19. >>> f.clean('foo@example.com')
  20. u'foo@example.com'
  21. >>> f.clean('invalid email address')
  22. Traceback (most recent call last):
  23. ...
  24. ValidationError: [u'Enter a valid email address.']
  25. .. _core-field-arguments:
  26. Core field arguments
  27. --------------------
  28. Each ``Field`` class constructor takes at least these arguments. Some
  29. ``Field`` classes take additional, field-specific arguments, but the following
  30. should *always* be accepted:
  31. ``required``
  32. ~~~~~~~~~~~~
  33. .. attribute:: Field.required
  34. By default, each ``Field`` class assumes the value is required, so if you pass
  35. an empty value -- either ``None`` or the empty string (``""``) -- then
  36. ``clean()`` will raise a ``ValidationError`` exception::
  37. >>> from django import forms
  38. >>> f = forms.CharField()
  39. >>> f.clean('foo')
  40. u'foo'
  41. >>> f.clean('')
  42. Traceback (most recent call last):
  43. ...
  44. ValidationError: [u'This field is required.']
  45. >>> f.clean(None)
  46. Traceback (most recent call last):
  47. ...
  48. ValidationError: [u'This field is required.']
  49. >>> f.clean(' ')
  50. u' '
  51. >>> f.clean(0)
  52. u'0'
  53. >>> f.clean(True)
  54. u'True'
  55. >>> f.clean(False)
  56. u'False'
  57. To specify that a field is *not* required, pass ``required=False`` to the
  58. ``Field`` constructor::
  59. >>> f = forms.CharField(required=False)
  60. >>> f.clean('foo')
  61. u'foo'
  62. >>> f.clean('')
  63. u''
  64. >>> f.clean(None)
  65. u''
  66. >>> f.clean(0)
  67. u'0'
  68. >>> f.clean(True)
  69. u'True'
  70. >>> f.clean(False)
  71. u'False'
  72. If a ``Field`` has ``required=False`` and you pass ``clean()`` an empty value,
  73. then ``clean()`` will return a *normalized* empty value rather than raising
  74. ``ValidationError``. For ``CharField``, this will be a Unicode empty string.
  75. For other ``Field`` classes, it might be ``None``. (This varies from field to
  76. field.)
  77. ``label``
  78. ~~~~~~~~~
  79. .. attribute:: Field.label
  80. The ``label`` argument lets you specify the "human-friendly" label for this
  81. field. This is used when the ``Field`` is displayed in a ``Form``.
  82. As explained in "Outputting forms as HTML" above, the default label for a
  83. ``Field`` is generated from the field name by converting all underscores to
  84. spaces and upper-casing the first letter. Specify ``label`` if that default
  85. behavior doesn't result in an adequate label.
  86. Here's a full example ``Form`` that implements ``label`` for two of its fields.
  87. We've specified ``auto_id=False`` to simplify the output::
  88. >>> from django import forms
  89. >>> class CommentForm(forms.Form):
  90. ... name = forms.CharField(label='Your name')
  91. ... url = forms.URLField(label='Your Web site', required=False)
  92. ... comment = forms.CharField()
  93. >>> f = CommentForm(auto_id=False)
  94. >>> print(f)
  95. <tr><th>Your name:</th><td><input type="text" name="name" /></td></tr>
  96. <tr><th>Your Web site:</th><td><input type="url" name="url" /></td></tr>
  97. <tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr>
  98. ``initial``
  99. ~~~~~~~~~~~
  100. .. attribute:: Field.initial
  101. The ``initial`` argument lets you specify the initial value to use when
  102. rendering this ``Field`` in an unbound ``Form``.
  103. To specify dynamic initial data, see the :attr:`Form.initial` parameter.
  104. The use-case for this is when you want to display an "empty" form in which a
  105. field is initialized to a particular value. For example::
  106. >>> from django import forms
  107. >>> class CommentForm(forms.Form):
  108. ... name = forms.CharField(initial='Your name')
  109. ... url = forms.URLField(initial='http://')
  110. ... comment = forms.CharField()
  111. >>> f = CommentForm(auto_id=False)
  112. >>> print(f)
  113. <tr><th>Name:</th><td><input type="text" name="name" value="Your name" /></td></tr>
  114. <tr><th>Url:</th><td><input type="url" name="url" value="http://" /></td></tr>
  115. <tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr>
  116. You may be thinking, why not just pass a dictionary of the initial values as
  117. data when displaying the form? Well, if you do that, you'll trigger validation,
  118. and the HTML output will include any validation errors::
  119. >>> class CommentForm(forms.Form):
  120. ... name = forms.CharField()
  121. ... url = forms.URLField()
  122. ... comment = forms.CharField()
  123. >>> default_data = {'name': 'Your name', 'url': 'http://'}
  124. >>> f = CommentForm(default_data, auto_id=False)
  125. >>> print(f)
  126. <tr><th>Name:</th><td><input type="text" name="name" value="Your name" /></td></tr>
  127. <tr><th>Url:</th><td><ul class="errorlist"><li>Enter a valid URL.</li></ul><input type="url" name="url" value="http://" /></td></tr>
  128. <tr><th>Comment:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="comment" /></td></tr>
  129. This is why ``initial`` values are only displayed for unbound forms. For bound
  130. forms, the HTML output will use the bound data.
  131. Also note that ``initial`` values are *not* used as "fallback" data in
  132. validation if a particular field's value is not given. ``initial`` values are
  133. *only* intended for initial form display::
  134. >>> class CommentForm(forms.Form):
  135. ... name = forms.CharField(initial='Your name')
  136. ... url = forms.URLField(initial='http://')
  137. ... comment = forms.CharField()
  138. >>> data = {'name': '', 'url': '', 'comment': 'Foo'}
  139. >>> f = CommentForm(data)
  140. >>> f.is_valid()
  141. False
  142. # The form does *not* fall back to using the initial values.
  143. >>> f.errors
  144. {'url': [u'This field is required.'], 'name': [u'This field is required.']}
  145. Instead of a constant, you can also pass any callable::
  146. >>> import datetime
  147. >>> class DateForm(forms.Form):
  148. ... day = forms.DateField(initial=datetime.date.today)
  149. >>> print(DateForm())
  150. <tr><th>Day:</th><td><input type="text" name="day" value="12/23/2008" /><td></tr>
  151. The callable will be evaluated only when the unbound form is displayed, not when it is defined.
  152. ``widget``
  153. ~~~~~~~~~~
  154. .. attribute:: Field.widget
  155. The ``widget`` argument lets you specify a ``Widget`` class to use when
  156. rendering this ``Field``. See :doc:`/ref/forms/widgets` for more information.
  157. ``help_text``
  158. ~~~~~~~~~~~~~
  159. .. attribute:: Field.help_text
  160. The ``help_text`` argument lets you specify descriptive text for this
  161. ``Field``. If you provide ``help_text``, it will be displayed next to the
  162. ``Field`` when the ``Field`` is rendered by one of the convenience ``Form``
  163. methods (e.g., ``as_ul()``).
  164. Here's a full example ``Form`` that implements ``help_text`` for two of its
  165. fields. We've specified ``auto_id=False`` to simplify the output::
  166. >>> from django import forms
  167. >>> class HelpTextContactForm(forms.Form):
  168. ... subject = forms.CharField(max_length=100, help_text='100 characters max.')
  169. ... message = forms.CharField()
  170. ... sender = forms.EmailField(help_text='A valid email address, please.')
  171. ... cc_myself = forms.BooleanField(required=False)
  172. >>> f = HelpTextContactForm(auto_id=False)
  173. >>> print(f.as_table())
  174. <tr><th>Subject:</th><td><input type="text" name="subject" maxlength="100" /><br /><span class="helptext">100 characters max.</span></td></tr>
  175. <tr><th>Message:</th><td><input type="text" name="message" /></td></tr>
  176. <tr><th>Sender:</th><td><input type="email" name="sender" /><br />A valid email address, please.</td></tr>
  177. <tr><th>Cc myself:</th><td><input type="checkbox" name="cc_myself" /></td></tr>
  178. >>> print(f.as_ul()))
  179. <li>Subject: <input type="text" name="subject" maxlength="100" /> <span class="helptext">100 characters max.</span></li>
  180. <li>Message: <input type="text" name="message" /></li>
  181. <li>Sender: <input type="email" name="sender" /> A valid email address, please.</li>
  182. <li>Cc myself: <input type="checkbox" name="cc_myself" /></li>
  183. >>> print(f.as_p())
  184. <p>Subject: <input type="text" name="subject" maxlength="100" /> <span class="helptext">100 characters max.</span></p>
  185. <p>Message: <input type="text" name="message" /></p>
  186. <p>Sender: <input type="email" name="sender" /> A valid email address, please.</p>
  187. <p>Cc myself: <input type="checkbox" name="cc_myself" /></p>
  188. ``error_messages``
  189. ~~~~~~~~~~~~~~~~~~
  190. .. attribute:: Field.error_messages
  191. The ``error_messages`` argument lets you override the default messages that the
  192. field will raise. Pass in a dictionary with keys matching the error messages you
  193. want to override. For example, here is the default error message::
  194. >>> from django import forms
  195. >>> generic = forms.CharField()
  196. >>> generic.clean('')
  197. Traceback (most recent call last):
  198. ...
  199. ValidationError: [u'This field is required.']
  200. And here is a custom error message::
  201. >>> name = forms.CharField(error_messages={'required': 'Please enter your name'})
  202. >>> name.clean('')
  203. Traceback (most recent call last):
  204. ...
  205. ValidationError: [u'Please enter your name']
  206. In the `built-in Field classes`_ section below, each ``Field`` defines the
  207. error message keys it uses.
  208. ``validators``
  209. ~~~~~~~~~~~~~~
  210. .. attribute:: Field.validators
  211. The ``validators`` argument lets you provide a list of validation functions
  212. for this field.
  213. See the :doc:`validators documentation </ref/validators>` for more information.
  214. ``localize``
  215. ~~~~~~~~~~~~
  216. .. attribute:: Field.localize
  217. The ``localize`` argument enables the localization of form data, input as well
  218. as the rendered output.
  219. See the :ref:`format localization <format-localization>` documentation for
  220. more information.
  221. .. _built-in fields:
  222. Built-in ``Field`` classes
  223. --------------------------
  224. Naturally, the ``forms`` library comes with a set of ``Field`` classes that
  225. represent common validation needs. This section documents each built-in field.
  226. For each field, we describe the default widget used if you don't specify
  227. ``widget``. We also specify the value returned when you provide an empty value
  228. (see the section on ``required`` above to understand what that means).
  229. ``BooleanField``
  230. ~~~~~~~~~~~~~~~~
  231. .. class:: BooleanField(**kwargs)
  232. * Default widget: :class:`CheckboxInput`
  233. * Empty value: ``False``
  234. * Normalizes to: A Python ``True`` or ``False`` value.
  235. * Validates that the value is ``True`` (e.g. the check box is checked) if
  236. the field has ``required=True``.
  237. * Error message keys: ``required``
  238. .. note::
  239. Since all ``Field`` subclasses have ``required=True`` by default, the
  240. validation condition here is important. If you want to include a boolean
  241. in your form that can be either ``True`` or ``False`` (e.g. a checked or
  242. unchecked checkbox), you must remember to pass in ``required=False`` when
  243. creating the ``BooleanField``.
  244. ``CharField``
  245. ~~~~~~~~~~~~~
  246. .. class:: CharField(**kwargs)
  247. * Default widget: :class:`TextInput`
  248. * Empty value: ``''`` (an empty string)
  249. * Normalizes to: A Unicode object.
  250. * Validates ``max_length`` or ``min_length``, if they are provided.
  251. Otherwise, all inputs are valid.
  252. * Error message keys: ``required``, ``max_length``, ``min_length``
  253. Has two optional arguments for validation:
  254. .. attribute:: max_length
  255. .. attribute:: min_length
  256. If provided, these arguments ensure that the string is at most or at least
  257. the given length.
  258. ``ChoiceField``
  259. ~~~~~~~~~~~~~~~
  260. .. class:: ChoiceField(**kwargs)
  261. * Default widget: :class:`Select`
  262. * Empty value: ``''`` (an empty string)
  263. * Normalizes to: A Unicode object.
  264. * Validates that the given value exists in the list of choices.
  265. * Error message keys: ``required``, ``invalid_choice``
  266. The ``invalid_choice`` error message may contain ``%(value)s``, which will be
  267. replaced with the selected choice.
  268. Takes one extra required argument:
  269. .. attribute:: choices
  270. An iterable (e.g., a list or tuple) of 2-tuples to use as choices for this
  271. field. This argument accepts the same formats as the ``choices`` argument
  272. to a model field. See the :ref:`model field reference documentation on
  273. choices <field-choices>` for more details.
  274. ``TypedChoiceField``
  275. ~~~~~~~~~~~~~~~~~~~~
  276. .. class:: TypedChoiceField(**kwargs)
  277. Just like a :class:`ChoiceField`, except :class:`TypedChoiceField` takes two
  278. extra arguments, ``coerce`` and ``empty_value``.
  279. * Default widget: :class:`Select`
  280. * Empty value: Whatever you've given as ``empty_value``
  281. * Normalizes to: A value of the type provided by the ``coerce`` argument.
  282. * Validates that the given value exists in the list of choices and can be
  283. coerced.
  284. * Error message keys: ``required``, ``invalid_choice``
  285. Takes extra arguments:
  286. .. attribute:: coerce
  287. A function that takes one argument and returns a coerced value. Examples
  288. include the built-in ``int``, ``float``, ``bool`` and other types. Defaults
  289. to an identity function. Note that coercion happens after input
  290. validation, so it is possible to coerce to a value not present in
  291. ``choices``.
  292. .. attribute:: empty_value
  293. The value to use to represent "empty." Defaults to the empty string;
  294. ``None`` is another common choice here. Note that this value will not be
  295. coerced by the function given in the ``coerce`` argument, so choose it
  296. accordingly.
  297. ``DateField``
  298. ~~~~~~~~~~~~~
  299. .. class:: DateField(**kwargs)
  300. * Default widget: :class:`DateInput`
  301. * Empty value: ``None``
  302. * Normalizes to: A Python ``datetime.date`` object.
  303. * Validates that the given value is either a ``datetime.date``,
  304. ``datetime.datetime`` or string formatted in a particular date format.
  305. * Error message keys: ``required``, ``invalid``
  306. Takes one optional argument:
  307. .. attribute:: input_formats
  308. A list of formats used to attempt to convert a string to a valid
  309. ``datetime.date`` object.
  310. If no ``input_formats`` argument is provided, the default input formats are::
  311. ['%Y-%m-%d', # '2006-10-25'
  312. '%m/%d/%Y', # '10/25/2006'
  313. '%m/%d/%y'] # '10/25/06'
  314. Additionally, if you specify :setting:`USE_L10N=False<USE_L10N>` in your settings, the
  315. following will also be included in the default input formats::
  316. ['%b %d %Y', # 'Oct 25 2006'
  317. '%b %d, %Y', # 'Oct 25, 2006'
  318. '%d %b %Y', # '25 Oct 2006'
  319. '%d %b, %Y', # '25 Oct, 2006'
  320. '%B %d %Y', # 'October 25 2006'
  321. '%B %d, %Y', # 'October 25, 2006'
  322. '%d %B %Y', # '25 October 2006'
  323. '%d %B, %Y'] # '25 October, 2006'
  324. See also :ref:`format localization <format-localization>`.
  325. ``DateTimeField``
  326. ~~~~~~~~~~~~~~~~~
  327. .. class:: DateTimeField(**kwargs)
  328. * Default widget: :class:`DateTimeInput`
  329. * Empty value: ``None``
  330. * Normalizes to: A Python ``datetime.datetime`` object.
  331. * Validates that the given value is either a ``datetime.datetime``,
  332. ``datetime.date`` or string formatted in a particular datetime format.
  333. * Error message keys: ``required``, ``invalid``
  334. Takes one optional argument:
  335. .. attribute:: input_formats
  336. A list of formats used to attempt to convert a string to a valid
  337. ``datetime.datetime`` object.
  338. If no ``input_formats`` argument is provided, the default input formats are::
  339. ['%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59'
  340. '%Y-%m-%d %H:%M', # '2006-10-25 14:30'
  341. '%Y-%m-%d', # '2006-10-25'
  342. '%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59'
  343. '%m/%d/%Y %H:%M', # '10/25/2006 14:30'
  344. '%m/%d/%Y', # '10/25/2006'
  345. '%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59'
  346. '%m/%d/%y %H:%M', # '10/25/06 14:30'
  347. '%m/%d/%y'] # '10/25/06'
  348. See also :ref:`format localization <format-localization>`.
  349. .. deprecated:: 1.7
  350. The ability to use :class:`SplitDateTimeWidget` with ``DateTimeField``
  351. has been deprecated and will be removed in Django 1.9. Use
  352. :class:`SplitDateTimeField` instead.
  353. ``DecimalField``
  354. ~~~~~~~~~~~~~~~~
  355. .. class:: DecimalField(**kwargs)
  356. * Default widget: :class:`NumberInput` when :attr:`Field.localize` is
  357. ``False``, else :class:`TextInput`.
  358. * Empty value: ``None``
  359. * Normalizes to: A Python ``decimal``.
  360. * Validates that the given value is a decimal. Leading and trailing
  361. whitespace is ignored.
  362. * Error message keys: ``required``, ``invalid``, ``max_value``,
  363. ``min_value``, ``max_digits``, ``max_decimal_places``,
  364. ``max_whole_digits``
  365. The ``max_value`` and ``min_value`` error messages may contain
  366. ``%(limit_value)s``, which will be substituted by the appropriate limit.
  367. .. versionchanged:: 1.6
  368. Similarly, the ``max_digits``, ``max_decimal_places`` and
  369. ``max_whole_digits`` error messages may contain ``%(max)s``.
  370. Takes four optional arguments:
  371. .. attribute:: max_value
  372. .. attribute:: min_value
  373. These control the range of values permitted in the field, and should be
  374. given as ``decimal.Decimal`` values.
  375. .. attribute:: max_digits
  376. The maximum number of digits (those before the decimal point plus those
  377. after the decimal point, with leading zeros stripped) permitted in the
  378. value.
  379. .. attribute:: decimal_places
  380. The maximum number of decimal places permitted.
  381. ``EmailField``
  382. ~~~~~~~~~~~~~~
  383. .. class:: EmailField(**kwargs)
  384. * Default widget: :class:`EmailInput`
  385. * Empty value: ``''`` (an empty string)
  386. * Normalizes to: A Unicode object.
  387. * Validates that the given value is a valid email address, using a
  388. moderately complex regular expression.
  389. * Error message keys: ``required``, ``invalid``
  390. Has two optional arguments for validation, ``max_length`` and ``min_length``.
  391. If provided, these arguments ensure that the string is at most or at least the
  392. given length.
  393. ``FileField``
  394. ~~~~~~~~~~~~~
  395. .. class:: FileField(**kwargs)
  396. * Default widget: :class:`ClearableFileInput`
  397. * Empty value: ``None``
  398. * Normalizes to: An ``UploadedFile`` object that wraps the file content
  399. and file name into a single object.
  400. * Can validate that non-empty file data has been bound to the form.
  401. * Error message keys: ``required``, ``invalid``, ``missing``, ``empty``,
  402. ``max_length``
  403. Has two optional arguments for validation, ``max_length`` and
  404. ``allow_empty_file``. If provided, these ensure that the file name is at
  405. most the given length, and that validation will succeed even if the file
  406. content is empty.
  407. To learn more about the ``UploadedFile`` object, see the :doc:`file uploads
  408. documentation </topics/http/file-uploads>`.
  409. When you use a ``FileField`` in a form, you must also remember to
  410. :ref:`bind the file data to the form <binding-uploaded-files>`.
  411. The ``max_length`` error refers to the length of the filename. In the error
  412. message for that key, ``%(max)d`` will be replaced with the maximum filename
  413. length and ``%(length)d`` will be replaced with the current filename length.
  414. ``FilePathField``
  415. ~~~~~~~~~~~~~~~~~
  416. .. class:: FilePathField(**kwargs)
  417. * Default widget: :class:`Select`
  418. * Empty value: ``None``
  419. * Normalizes to: A unicode object
  420. * Validates that the selected choice exists in the list of choices.
  421. * Error message keys: ``required``, ``invalid_choice``
  422. The field allows choosing from files inside a certain directory. It takes three
  423. extra arguments; only ``path`` is required:
  424. .. attribute:: path
  425. The absolute path to the directory whose contents you want listed. This
  426. directory must exist.
  427. .. attribute:: recursive
  428. If ``False`` (the default) only the direct contents of ``path`` will be
  429. offered as choices. If ``True``, the directory will be descended into
  430. recursively and all descendants will be listed as choices.
  431. .. attribute:: match
  432. A regular expression pattern; only files with names matching this expression
  433. will be allowed as choices.
  434. .. attribute:: allow_files
  435. Optional. Either ``True`` or ``False``. Default is ``True``. Specifies
  436. whether files in the specified location should be included. Either this or
  437. :attr:`allow_folders` must be ``True``.
  438. .. attribute:: allow_folders
  439. Optional. Either ``True`` or ``False``. Default is ``False``. Specifies
  440. whether folders in the specified location should be included. Either this or
  441. :attr:`allow_files` must be ``True``.
  442. ``FloatField``
  443. ~~~~~~~~~~~~~~
  444. .. class:: FloatField(**kwargs)
  445. * Default widget: :class:`NumberInput` when :attr:`Field.localize` is
  446. ``False``, else :class:`TextInput`.
  447. * Empty value: ``None``
  448. * Normalizes to: A Python float.
  449. * Validates that the given value is an float. Leading and trailing
  450. whitespace is allowed, as in Python's ``float()`` function.
  451. * Error message keys: ``required``, ``invalid``, ``max_value``,
  452. ``min_value``
  453. Takes two optional arguments for validation, ``max_value`` and ``min_value``.
  454. These control the range of values permitted in the field.
  455. ``ImageField``
  456. ~~~~~~~~~~~~~~
  457. .. class:: ImageField(**kwargs)
  458. * Default widget: :class:`ClearableFileInput`
  459. * Empty value: ``None``
  460. * Normalizes to: An ``UploadedFile`` object that wraps the file content
  461. and file name into a single object.
  462. * Validates that file data has been bound to the form, and that the
  463. file is of an image format understood by Pillow.
  464. * Error message keys: ``required``, ``invalid``, ``missing``, ``empty``,
  465. ``invalid_image``
  466. Using an ``ImageField`` requires that `Pillow`_ is installed with support
  467. for the image formats you use. If you encounter a ``corrupt image`` error
  468. when you upload an image, it usually means that Pillow doesn't understand
  469. its format. To fix this, install the appropriate library and reinstall
  470. Pillow.
  471. When you use an ``ImageField`` on a form, you must also remember to
  472. :ref:`bind the file data to the form <binding-uploaded-files>`.
  473. .. _Pillow: http://python-imaging.github.io/Pillow/
  474. ``IntegerField``
  475. ~~~~~~~~~~~~~~~~
  476. .. class:: IntegerField(**kwargs)
  477. * Default widget: :class:`NumberInput` when :attr:`Field.localize` is
  478. ``False``, else :class:`TextInput`.
  479. * Empty value: ``None``
  480. * Normalizes to: A Python integer or long integer.
  481. * Validates that the given value is an integer. Leading and trailing
  482. whitespace is allowed, as in Python's ``int()`` function.
  483. * Error message keys: ``required``, ``invalid``, ``max_value``,
  484. ``min_value``
  485. The ``max_value`` and ``min_value`` error messages may contain
  486. ``%(limit_value)s``, which will be substituted by the appropriate limit.
  487. Takes two optional arguments for validation:
  488. .. attribute:: max_value
  489. .. attribute:: min_value
  490. These control the range of values permitted in the field.
  491. ``IPAddressField``
  492. ~~~~~~~~~~~~~~~~~~
  493. .. class:: IPAddressField(**kwargs)
  494. .. deprecated:: 1.7
  495. This field has been deprecated in favor of
  496. :class:`~django.forms.GenericIPAddressField`.
  497. * Default widget: :class:`TextInput`
  498. * Empty value: ``''`` (an empty string)
  499. * Normalizes to: A Unicode object.
  500. * Validates that the given value is a valid IPv4 address, using a regular
  501. expression.
  502. * Error message keys: ``required``, ``invalid``
  503. ``GenericIPAddressField``
  504. ~~~~~~~~~~~~~~~~~~~~~~~~~
  505. .. class:: GenericIPAddressField(**kwargs)
  506. A field containing either an IPv4 or an IPv6 address.
  507. * Default widget: :class:`TextInput`
  508. * Empty value: ``''`` (an empty string)
  509. * Normalizes to: A Unicode object. IPv6 addresses are
  510. normalized as described below.
  511. * Validates that the given value is a valid IP address.
  512. * Error message keys: ``required``, ``invalid``
  513. The IPv6 address normalization follows :rfc:`4291#section-2.2` section 2.2,
  514. including using the IPv4 format suggested in paragraph 3 of that section, like
  515. ``::ffff:192.0.2.0``. For example, ``2001:0::0:01`` would be normalized to
  516. ``2001::1``, and ``::ffff:0a0a:0a0a`` to ``::ffff:10.10.10.10``. All characters
  517. are converted to lowercase.
  518. Takes two optional arguments:
  519. .. attribute:: protocol
  520. Limits valid inputs to the specified protocol.
  521. Accepted values are ``both`` (default), ``IPv4``
  522. or ``IPv6``. Matching is case insensitive.
  523. .. attribute:: unpack_ipv4
  524. Unpacks IPv4 mapped addresses like ``::ffff:192.0.2.1``.
  525. If this option is enabled that address would be unpacked to
  526. ``192.0.2.1``. Default is disabled. Can only be used
  527. when ``protocol`` is set to ``'both'``.
  528. ``MultipleChoiceField``
  529. ~~~~~~~~~~~~~~~~~~~~~~~
  530. .. class:: MultipleChoiceField(**kwargs)
  531. * Default widget: :class:`SelectMultiple`
  532. * Empty value: ``[]`` (an empty list)
  533. * Normalizes to: A list of Unicode objects.
  534. * Validates that every value in the given list of values exists in the list
  535. of choices.
  536. * Error message keys: ``required``, ``invalid_choice``, ``invalid_list``
  537. The ``invalid_choice`` error message may contain ``%(value)s``, which will be
  538. replaced with the selected choice.
  539. Takes one extra required argument, ``choices``, as for ``ChoiceField``.
  540. ``TypedMultipleChoiceField``
  541. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  542. .. class:: TypedMultipleChoiceField(**kwargs)
  543. Just like a :class:`MultipleChoiceField`, except :class:`TypedMultipleChoiceField`
  544. takes two extra arguments, ``coerce`` and ``empty_value``.
  545. * Default widget: :class:`SelectMultiple`
  546. * Empty value: Whatever you've given as ``empty_value``
  547. * Normalizes to: A list of values of the type provided by the ``coerce``
  548. argument.
  549. * Validates that the given values exists in the list of choices and can be
  550. coerced.
  551. * Error message keys: ``required``, ``invalid_choice``
  552. The ``invalid_choice`` error message may contain ``%(value)s``, which will be
  553. replaced with the selected choice.
  554. Takes two extra arguments, ``coerce`` and ``empty_value``, as for ``TypedChoiceField``.
  555. ``NullBooleanField``
  556. ~~~~~~~~~~~~~~~~~~~~
  557. .. class:: NullBooleanField(**kwargs)
  558. * Default widget: :class:`NullBooleanSelect`
  559. * Empty value: ``None``
  560. * Normalizes to: A Python ``True``, ``False`` or ``None`` value.
  561. * Validates nothing (i.e., it never raises a ``ValidationError``).
  562. ``RegexField``
  563. ~~~~~~~~~~~~~~
  564. .. class:: RegexField(**kwargs)
  565. * Default widget: :class:`TextInput`
  566. * Empty value: ``''`` (an empty string)
  567. * Normalizes to: A Unicode object.
  568. * Validates that the given value matches against a certain regular
  569. expression.
  570. * Error message keys: ``required``, ``invalid``
  571. Takes one required argument:
  572. .. attribute:: regex
  573. A regular expression specified either as a string or a compiled regular
  574. expression object.
  575. Also takes ``max_length`` and ``min_length``, which work just as they do for
  576. ``CharField``.
  577. The optional argument ``error_message`` is also accepted for backwards
  578. compatibility. The preferred way to provide an error message is to use the
  579. ``error_messages`` argument, passing a dictionary with ``'invalid'`` as a key
  580. and the error message as the value.
  581. ``SlugField``
  582. ~~~~~~~~~~~~~
  583. .. class:: SlugField(**kwargs)
  584. * Default widget: :class:`TextInput`
  585. * Empty value: ``''`` (an empty string)
  586. * Normalizes to: A Unicode object.
  587. * Validates that the given value contains only letters, numbers,
  588. underscores, and hyphens.
  589. * Error messages: ``required``, ``invalid``
  590. This field is intended for use in representing a model
  591. :class:`~django.db.models.SlugField` in forms.
  592. ``TimeField``
  593. ~~~~~~~~~~~~~
  594. .. class:: TimeField(**kwargs)
  595. * Default widget: :class:`TextInput`
  596. * Empty value: ``None``
  597. * Normalizes to: A Python ``datetime.time`` object.
  598. * Validates that the given value is either a ``datetime.time`` or string
  599. formatted in a particular time format.
  600. * Error message keys: ``required``, ``invalid``
  601. Takes one optional argument:
  602. .. attribute:: input_formats
  603. A list of formats used to attempt to convert a string to a valid
  604. ``datetime.time`` object.
  605. If no ``input_formats`` argument is provided, the default input formats are::
  606. '%H:%M:%S', # '14:30:59'
  607. '%H:%M', # '14:30'
  608. ``URLField``
  609. ~~~~~~~~~~~~
  610. .. class:: URLField(**kwargs)
  611. * Default widget: :class:`URLInput`
  612. * Empty value: ``''`` (an empty string)
  613. * Normalizes to: A Unicode object.
  614. * Validates that the given value is a valid URL.
  615. * Error message keys: ``required``, ``invalid``
  616. Takes the following optional arguments:
  617. .. attribute:: max_length
  618. .. attribute:: min_length
  619. These are the same as ``CharField.max_length`` and ``CharField.min_length``.
  620. Slightly complex built-in ``Field`` classes
  621. -------------------------------------------
  622. ``ComboField``
  623. ~~~~~~~~~~~~~~
  624. .. class:: ComboField(**kwargs)
  625. * Default widget: :class:`TextInput`
  626. * Empty value: ``''`` (an empty string)
  627. * Normalizes to: A Unicode object.
  628. * Validates that the given value against each of the fields specified
  629. as an argument to the ``ComboField``.
  630. * Error message keys: ``required``, ``invalid``
  631. Takes one extra required argument:
  632. .. attribute:: fields
  633. The list of fields that should be used to validate the field's value (in
  634. the order in which they are provided).
  635. >>> from django.forms import ComboField
  636. >>> f = ComboField(fields=[CharField(max_length=20), EmailField()])
  637. >>> f.clean('test@example.com')
  638. u'test@example.com'
  639. >>> f.clean('longemailaddress@example.com')
  640. Traceback (most recent call last):
  641. ...
  642. ValidationError: [u'Ensure this value has at most 20 characters (it has 28).']
  643. ``MultiValueField``
  644. ~~~~~~~~~~~~~~~~~~~
  645. .. class:: MultiValueField(fields=(), **kwargs)
  646. * Default widget: :class:`TextInput`
  647. * Empty value: ``''`` (an empty string)
  648. * Normalizes to: the type returned by the ``compress`` method of the subclass.
  649. * Validates that the given value against each of the fields specified
  650. as an argument to the ``MultiValueField``.
  651. * Error message keys: ``required``, ``invalid``, ``incomplete``
  652. Aggregates the logic of multiple fields that together produce a single
  653. value.
  654. This field is abstract and must be subclassed. In contrast with the
  655. single-value fields, subclasses of :class:`MultiValueField` must not
  656. implement :meth:`~django.forms.Field.clean` but instead - implement
  657. :meth:`~MultiValueField.compress`.
  658. Takes one extra required argument:
  659. .. attribute:: fields
  660. A tuple of fields whose values are cleaned and subsequently combined
  661. into a single value. Each value of the field is cleaned by the
  662. corresponding field in ``fields`` -- the first value is cleaned by the
  663. first field, the second value is cleaned by the second field, etc.
  664. Once all fields are cleaned, the list of clean values is combined into
  665. a single value by :meth:`~MultiValueField.compress`.
  666. Also takes one extra optional argument:
  667. .. attribute:: require_all_fields
  668. .. versionadded:: 1.7
  669. Defaults to ``True``, in which case a ``required`` validation error
  670. will be raised if no value is supplied for any field.
  671. When set to ``False``, the :attr:`Field.required` attribute can be set
  672. to ``False`` for individual fields to make them optional. If no value
  673. is supplied for a required field, an ``incomplete`` validation error
  674. will be raised.
  675. A default ``incomplete`` error message can be defined on the
  676. :class:`MultiValueField` subclass, or different messages can be defined
  677. on each individual field. For example::
  678. from django.core.validators import RegexValidator
  679. class PhoneField(MultiValueField):
  680. def __init__(self, *args, **kwargs):
  681. # Define one message for all fields.
  682. error_messages = {
  683. 'incomplete': 'Enter a country code and phone number.',
  684. }
  685. # Or define a different message for each field.
  686. fields = (
  687. CharField(error_messages={'incomplete': 'Enter a country code.'},
  688. validators=[RegexValidator(r'^\d+$', 'Enter a valid country code.')]),
  689. CharField(error_messages={'incomplete': 'Enter a phone number.'},
  690. validators=[RegexValidator(r'^\d+$', 'Enter a valid phone number.')]),
  691. CharField(validators=[RegexValidator(r'^\d+$', 'Enter a valid extension.')],
  692. required=False),
  693. )
  694. super(PhoneField, self).__init__(
  695. error_messages=error_messages, fields=fields,
  696. require_all_fields=False, *args, **kwargs)
  697. .. attribute:: MultiValueField.widget
  698. Must be a subclass of :class:`django.forms.MultiWidget`.
  699. Default value is :class:`~django.forms.TextInput`, which
  700. probably is not very useful in this case.
  701. .. method:: compress(data_list)
  702. Takes a list of valid values and returns a "compressed" version of
  703. those values -- in a single value. For example,
  704. :class:`SplitDateTimeField` is a subclass which combines a time field
  705. and a date field into a ``datetime`` object.
  706. This method must be implemented in the subclasses.
  707. ``SplitDateTimeField``
  708. ~~~~~~~~~~~~~~~~~~~~~~
  709. .. class:: SplitDateTimeField(**kwargs)
  710. * Default widget: :class:`SplitDateTimeWidget`
  711. * Empty value: ``None``
  712. * Normalizes to: A Python ``datetime.datetime`` object.
  713. * Validates that the given value is a ``datetime.datetime`` or string
  714. formatted in a particular datetime format.
  715. * Error message keys: ``required``, ``invalid``, ``invalid_date``,
  716. ``invalid_time``
  717. Takes two optional arguments:
  718. .. attribute:: input_date_formats
  719. A list of formats used to attempt to convert a string to a valid
  720. ``datetime.date`` object.
  721. If no ``input_date_formats`` argument is provided, the default input formats
  722. for ``DateField`` are used.
  723. .. attribute:: input_time_formats
  724. A list of formats used to attempt to convert a string to a valid
  725. ``datetime.time`` object.
  726. If no ``input_time_formats`` argument is provided, the default input formats
  727. for ``TimeField`` are used.
  728. Fields which handle relationships
  729. ---------------------------------
  730. Two fields are available for representing relationships between
  731. models: :class:`ModelChoiceField` and
  732. :class:`ModelMultipleChoiceField`. Both of these fields require a
  733. single ``queryset`` parameter that is used to create the choices for
  734. the field. Upon form validation, these fields will place either one
  735. model object (in the case of ``ModelChoiceField``) or multiple model
  736. objects (in the case of ``ModelMultipleChoiceField``) into the
  737. ``cleaned_data`` dictionary of the form.
  738. ``ModelChoiceField``
  739. ~~~~~~~~~~~~~~~~~~~~
  740. .. class:: ModelChoiceField(**kwargs)
  741. * Default widget: :class:`Select`
  742. * Empty value: ``None``
  743. * Normalizes to: A model instance.
  744. * Validates that the given id exists in the queryset.
  745. * Error message keys: ``required``, ``invalid_choice``
  746. Allows the selection of a single model object, suitable for representing a
  747. foreign key. Note that the default widget for ``ModelChoiceField`` becomes
  748. impractical when the number of entries increases. You should avoid using it
  749. for more than 100 items.
  750. A single argument is required:
  751. .. attribute:: queryset
  752. A ``QuerySet`` of model objects from which the choices for the
  753. field will be derived, and which will be used to validate the
  754. user's selection.
  755. ``ModelChoiceField`` also takes two optional arguments:
  756. .. attribute:: empty_label
  757. By default the ``<select>`` widget used by ``ModelChoiceField`` will have an
  758. empty choice at the top of the list. You can change the text of this
  759. label (which is ``"---------"`` by default) with the ``empty_label``
  760. attribute, or you can disable the empty label entirely by setting
  761. ``empty_label`` to ``None``::
  762. # A custom empty label
  763. field1 = forms.ModelChoiceField(queryset=..., empty_label="(Nothing)")
  764. # No empty label
  765. field2 = forms.ModelChoiceField(queryset=..., empty_label=None)
  766. Note that if a ``ModelChoiceField`` is required and has a default
  767. initial value, no empty choice is created (regardless of the value
  768. of ``empty_label``).
  769. .. attribute:: to_field_name
  770. This optional argument is used to specify the field to use as the value
  771. of the choices in the field's widget. By default it is set to ``None``,
  772. in which case the primary key of each object will be used. For example::
  773. # No custom to_field_name
  774. field1 = forms.ModelChoiceField(queryset=...)
  775. would yield:
  776. .. code-block:: html
  777. <select id="id_field1" name="field1">
  778. <option value="obj1.pk">Object1</option>
  779. <option value="obj2.pk">Object2</option>
  780. ...
  781. </select>
  782. and::
  783. # to_field_name provided
  784. field2 = forms.ModelChoiceField(queryset=..., to_field_name="name")
  785. would yield:
  786. .. code-block:: html
  787. <select id="id_field2" name="field2">
  788. <option value="obj1.name">Object1</option>
  789. <option value="obj2.name">Object2</option>
  790. ...
  791. </select>
  792. The ``__str__`` (``__unicode__`` on Python 2) method of the model will be
  793. called to generate string representations of the objects for use in the
  794. field's choices; to provide customized representations, subclass
  795. ``ModelChoiceField`` and override ``label_from_instance``. This method will
  796. receive a model object, and should return a string suitable for representing
  797. it. For example::
  798. from django.forms import ModelChoiceField
  799. class MyModelChoiceField(ModelChoiceField):
  800. def label_from_instance(self, obj):
  801. return "My Object #%i" % obj.id
  802. ``ModelMultipleChoiceField``
  803. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  804. .. class:: ModelMultipleChoiceField(**kwargs)
  805. * Default widget: :class:`SelectMultiple`
  806. * Empty value: An empty ``QuerySet`` (self.queryset.none())
  807. * Normalizes to: A ``QuerySet`` of model instances.
  808. * Validates that every id in the given list of values exists in the
  809. queryset.
  810. * Error message keys: ``required``, ``list``, ``invalid_choice``,
  811. ``invalid_pk_value``
  812. .. versionchanged:: 1.6
  813. The ``invalid_choice`` message may contain ``%(value)s`` and the
  814. ``invalid_pk_value`` message may contain ``%(pk)s``, which will be
  815. substituted by the appropriate values.
  816. Allows the selection of one or more model objects, suitable for
  817. representing a many-to-many relation. As with :class:`ModelChoiceField`,
  818. you can use ``label_from_instance`` to customize the object
  819. representations, and ``queryset`` is a required parameter:
  820. .. attribute:: queryset
  821. A ``QuerySet`` of model objects from which the choices for the
  822. field will be derived, and which will be used to validate the
  823. user's selection.
  824. Creating custom fields
  825. ----------------------
  826. If the built-in ``Field`` classes don't meet your needs, you can easily create
  827. custom ``Field`` classes. To do this, just create a subclass of
  828. ``django.forms.Field``. Its only requirements are that it implement a
  829. ``clean()`` method and that its ``__init__()`` method accept the core arguments
  830. mentioned above (``required``, ``label``, ``initial``, ``widget``,
  831. ``help_text``).