fields.txt 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792
  1. .. _ref-forms-fields:
  2. ===========
  3. Form fields
  4. ===========
  5. .. module:: django.forms.fields
  6. :synopsis: Django's built-in form fields.
  7. .. currentmodule:: django.forms
  8. .. class:: Field(**kwargs)
  9. When you create a ``Form`` class, the most important part is defining the
  10. fields of the form. Each field has custom validation logic, along with a few
  11. other hooks.
  12. .. method:: Field.clean(value)
  13. Although the primary way you'll use ``Field`` classes is in ``Form`` classes,
  14. you can also instantiate them and use them directly to get a better idea of
  15. how they work. Each ``Field`` instance has a ``clean()`` method, which takes
  16. a single argument and either raises a ``django.forms.ValidationError``
  17. exception or returns the clean value::
  18. >>> f = forms.EmailField()
  19. >>> f.clean('foo@example.com')
  20. u'foo@example.com'
  21. >>> f.clean(u'foo@example.com')
  22. u'foo@example.com'
  23. >>> f.clean('invalid e-mail address')
  24. Traceback (most recent call last):
  25. ...
  26. ValidationError: [u'Enter a valid e-mail address.']
  27. Core field arguments
  28. --------------------
  29. Each ``Field`` class constructor takes at least these arguments. Some
  30. ``Field`` classes take additional, field-specific arguments, but the following
  31. should *always* be accepted:
  32. ``required``
  33. ~~~~~~~~~~~~
  34. .. attribute:: Field.required
  35. By default, each ``Field`` class assumes the value is required, so if you pass
  36. an empty value -- either ``None`` or the empty string (``""``) -- then
  37. ``clean()`` will raise a ``ValidationError`` exception::
  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. >>> class CommentForm(forms.Form):
  89. ... name = forms.CharField(label='Your name')
  90. ... url = forms.URLField(label='Your Web site', required=False)
  91. ... comment = forms.CharField()
  92. >>> f = CommentForm(auto_id=False)
  93. >>> print f
  94. <tr><th>Your name:</th><td><input type="text" name="name" /></td></tr>
  95. <tr><th>Your Web site:</th><td><input type="text" name="url" /></td></tr>
  96. <tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr>
  97. ``initial``
  98. ~~~~~~~~~~~
  99. .. attribute:: Field.initial
  100. The ``initial`` argument lets you specify the initial value to use when
  101. rendering this ``Field`` in an unbound ``Form``.
  102. The use-case for this is when you want to display an "empty" form in which a
  103. field is initialized to a particular value. For example::
  104. >>> class CommentForm(forms.Form):
  105. ... name = forms.CharField(initial='Your name')
  106. ... url = forms.URLField(initial='http://')
  107. ... comment = forms.CharField()
  108. >>> f = CommentForm(auto_id=False)
  109. >>> print f
  110. <tr><th>Name:</th><td><input type="text" name="name" value="Your name" /></td></tr>
  111. <tr><th>Url:</th><td><input type="text" name="url" value="http://" /></td></tr>
  112. <tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr>
  113. You may be thinking, why not just pass a dictionary of the initial values as
  114. data when displaying the form? Well, if you do that, you'll trigger validation,
  115. and the HTML output will include any validation errors::
  116. >>> class CommentForm(forms.Form):
  117. ... name = forms.CharField()
  118. ... url = forms.URLField()
  119. ... comment = forms.CharField()
  120. >>> default_data = {'name': 'Your name', 'url': 'http://'}
  121. >>> f = CommentForm(default_data, auto_id=False)
  122. >>> print f
  123. <tr><th>Name:</th><td><input type="text" name="name" value="Your name" /></td></tr>
  124. <tr><th>Url:</th><td><ul class="errorlist"><li>Enter a valid URL.</li></ul><input type="text" name="url" value="http://" /></td></tr>
  125. <tr><th>Comment:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="comment" /></td></tr>
  126. This is why ``initial`` values are only displayed for unbound forms. For bound
  127. forms, the HTML output will use the bound data.
  128. Also note that ``initial`` values are *not* used as "fallback" data in
  129. validation if a particular field's value is not given. ``initial`` values are
  130. *only* intended for initial form display::
  131. >>> class CommentForm(forms.Form):
  132. ... name = forms.CharField(initial='Your name')
  133. ... url = forms.URLField(initial='http://')
  134. ... comment = forms.CharField()
  135. >>> data = {'name': '', 'url': '', 'comment': 'Foo'}
  136. >>> f = CommentForm(data)
  137. >>> f.is_valid()
  138. False
  139. # The form does *not* fall back to using the initial values.
  140. >>> f.errors
  141. {'url': [u'This field is required.'], 'name': [u'This field is required.']}
  142. ``widget``
  143. ~~~~~~~~~~
  144. .. attribute:: Field.widget
  145. The ``widget`` argument lets you specify a ``Widget`` class to use when
  146. rendering this ``Field``. See :ref:`ref-forms-widgets` for more information.
  147. ``help_text``
  148. ~~~~~~~~~~~~~
  149. .. attribute:: Field.help_text
  150. The ``help_text`` argument lets you specify descriptive text for this
  151. ``Field``. If you provide ``help_text``, it will be displayed next to the
  152. ``Field`` when the ``Field`` is rendered by one of the convenience ``Form``
  153. methods (e.g., ``as_ul()``).
  154. Here's a full example ``Form`` that implements ``help_text`` for two of its
  155. fields. We've specified ``auto_id=False`` to simplify the output::
  156. >>> class HelpTextContactForm(forms.Form):
  157. ... subject = forms.CharField(max_length=100, help_text='100 characters max.')
  158. ... message = forms.CharField()
  159. ... sender = forms.EmailField(help_text='A valid e-mail address, please.')
  160. ... cc_myself = forms.BooleanField(required=False)
  161. >>> f = HelpTextContactForm(auto_id=False)
  162. >>> print f.as_table()
  163. <tr><th>Subject:</th><td><input type="text" name="subject" maxlength="100" /><br />100 characters max.</td></tr>
  164. <tr><th>Message:</th><td><input type="text" name="message" /></td></tr>
  165. <tr><th>Sender:</th><td><input type="text" name="sender" /><br />A valid e-mail address, please.</td></tr>
  166. <tr><th>Cc myself:</th><td><input type="checkbox" name="cc_myself" /></td></tr>
  167. >>> print f.as_ul()
  168. <li>Subject: <input type="text" name="subject" maxlength="100" /> 100 characters max.</li>
  169. <li>Message: <input type="text" name="message" /></li>
  170. <li>Sender: <input type="text" name="sender" /> A valid e-mail address, please.</li>
  171. <li>Cc myself: <input type="checkbox" name="cc_myself" /></li>
  172. >>> print f.as_p()
  173. <p>Subject: <input type="text" name="subject" maxlength="100" /> 100 characters max.</p>
  174. <p>Message: <input type="text" name="message" /></p>
  175. <p>Sender: <input type="text" name="sender" /> A valid e-mail address, please.</p>
  176. <p>Cc myself: <input type="checkbox" name="cc_myself" /></p>
  177. ``error_messages``
  178. ~~~~~~~~~~~~~~~~~~
  179. .. versionadded:: 1.0
  180. .. attribute:: Field.error_messages
  181. The ``error_messages`` argument lets you override the default messages that the
  182. field will raise. Pass in a dictionary with keys matching the error messages you
  183. want to override. For example, here is the default error message::
  184. >>> generic = forms.CharField()
  185. >>> generic.clean('')
  186. Traceback (most recent call last):
  187. ...
  188. ValidationError: [u'This field is required.']
  189. And here is a custom error message::
  190. >>> name = forms.CharField(error_messages={'required': 'Please enter your name'})
  191. >>> name.clean('')
  192. Traceback (most recent call last):
  193. ...
  194. ValidationError: [u'Please enter your name']
  195. In the `built-in Field classes`_ section below, each ``Field`` defines the
  196. error message keys it uses.
  197. Dynamic initial values
  198. ----------------------
  199. The ``initial`` argument to ``Field`` (explained above) lets you hard-code the
  200. initial value for a ``Field`` -- but what if you want to declare the initial
  201. value at runtime? For example, you might want to fill in a ``username`` field
  202. with the username of the current session.
  203. To accomplish this, use the ``initial`` argument to a ``Form``. This argument,
  204. if given, should be a dictionary mapping field names to initial values. Only
  205. include the fields for which you're specifying an initial value; it's not
  206. necessary to include every field in your form. For example::
  207. >>> class CommentForm(forms.Form):
  208. ... name = forms.CharField()
  209. ... url = forms.URLField()
  210. ... comment = forms.CharField()
  211. >>> f = CommentForm(initial={'name': 'your username'}, auto_id=False)
  212. >>> print f
  213. <tr><th>Name:</th><td><input type="text" name="name" value="your username" /></td></tr>
  214. <tr><th>Url:</th><td><input type="text" name="url" /></td></tr>
  215. <tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr>
  216. >>> f = CommentForm(initial={'name': 'another username'}, auto_id=False)
  217. >>> print f
  218. <tr><th>Name:</th><td><input type="text" name="name" value="another username" /></td></tr>
  219. <tr><th>Url:</th><td><input type="text" name="url" /></td></tr>
  220. <tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr>
  221. Just like the ``initial`` parameter to ``Field``, these values are only
  222. displayed for unbound forms, and they're not used as fallback values if a
  223. particular value isn't provided.
  224. Finally, note that if a ``Field`` defines ``initial`` *and* you include
  225. ``initial`` when instantiating the ``Form``, then the latter ``initial`` will
  226. have precedence. In this example, ``initial`` is provided both at the field
  227. level and at the form instance level, and the latter gets precedence::
  228. >>> class CommentForm(forms.Form):
  229. ... name = forms.CharField(initial='class')
  230. ... url = forms.URLField()
  231. ... comment = forms.CharField()
  232. >>> f = CommentForm(initial={'name': 'instance'}, auto_id=False)
  233. >>> print f
  234. <tr><th>Name:</th><td><input type="text" name="name" value="instance" /></td></tr>
  235. <tr><th>Url:</th><td><input type="text" name="url" /></td></tr>
  236. <tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr>
  237. Built-in ``Field`` classes
  238. --------------------------
  239. Naturally, the ``forms`` library comes with a set of ``Field`` classes that
  240. represent common validation needs. This section documents each built-in field.
  241. For each field, we describe the default widget used if you don't specify
  242. ``widget``. We also specify the value returned when you provide an empty value
  243. (see the section on ``required`` above to understand what that means).
  244. ``BooleanField``
  245. ~~~~~~~~~~~~~~~~
  246. .. class:: BooleanField(**kwargs)
  247. * Default widget: ``CheckboxInput``
  248. * Empty value: ``False``
  249. * Normalizes to: A Python ``True`` or ``False`` value.
  250. * Validates that the check box is checked (i.e. the value is ``True``) if
  251. the field has ``required=True``.
  252. * Error message keys: ``required``
  253. .. versionchanged:: 1.0
  254. The empty value for a ``CheckboxInput`` (and hence the standard ``BooleanField``)
  255. has changed to return ``False`` instead of ``None`` in the development version.
  256. .. note::
  257. Since all ``Field`` subclasses have ``required=True`` by default, the
  258. validation condition here is important. If you want to include a checkbox
  259. in your form that can be either checked or unchecked, you must remember to
  260. pass in ``required=False`` when creating the ``BooleanField``.
  261. ``CharField``
  262. ~~~~~~~~~~~~~
  263. .. class:: CharField(**kwargs)
  264. * Default widget: ``TextInput``
  265. * Empty value: ``''`` (an empty string)
  266. * Normalizes to: A Unicode object.
  267. * Validates ``max_length`` or ``min_length``, if they are provided.
  268. Otherwise, all inputs are valid.
  269. * Error message keys: ``required``, ``max_length``, ``min_length``
  270. Has two optional arguments for validation:
  271. .. attribute:: CharField.max_length
  272. .. attribute:: CharField.min_length
  273. If provided, these arguments ensure that the string is at most or at least
  274. the given length.
  275. ``ChoiceField``
  276. ~~~~~~~~~~~~~~~
  277. .. class:: ChoiceField(**kwargs)
  278. * Default widget: ``Select``
  279. * Empty value: ``''`` (an empty string)
  280. * Normalizes to: A Unicode object.
  281. * Validates that the given value exists in the list of choices.
  282. * Error message keys: ``required``, ``invalid_choice``
  283. Takes one extra required argument:
  284. .. attribute:: ChoiceField.choices
  285. An iterable (e.g., a list or tuple) of 2-tuples to use as choices for this
  286. field.
  287. ``TypedChoiceField``
  288. ~~~~~~~~~~~~~~~~~~~~
  289. .. class:: TypedChoiceField(**kwargs)
  290. Just like a :class:`ChoiceField`, except :class:`TypedChoiceField` takes an
  291. extra ``coerce`` argument.
  292. * Default widget: ``Select``
  293. * Empty value: Whatever you've given as ``empty_value``
  294. * Normalizes to: the value returned by the ``coerce`` argument.
  295. * Validates that the given value exists in the list of choices.
  296. * Error message keys: ``required``, ``invalid_choice``
  297. Takes extra arguments:
  298. .. attribute:: TypedChoiceField.coerce
  299. A function that takes one argument and returns a coerced value. Examples
  300. include the built-in ``int``, ``float``, ``bool`` and other types. Defaults
  301. to an identity function.
  302. .. attribute:: TypedChoiceField.empty_value
  303. The value to use to represent "empty." Defaults to the empty string;
  304. ``None`` is another common choice here.
  305. ``DateField``
  306. ~~~~~~~~~~~~~
  307. .. class:: DateField(**kwargs)
  308. * Default widget: ``TextInput``
  309. * Empty value: ``None``
  310. * Normalizes to: A Python ``datetime.date`` object.
  311. * Validates that the given value is either a ``datetime.date``,
  312. ``datetime.datetime`` or string formatted in a particular date format.
  313. * Error message keys: ``required``, ``invalid``
  314. Takes one optional argument:
  315. .. attribute:: DateField.input_formats
  316. A list of formats used to attempt to convert a string to a valid
  317. ``datetime.date`` object.
  318. If no ``input_formats`` argument is provided, the default input formats are::
  319. '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06'
  320. '%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006'
  321. '%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006'
  322. '%B %d %Y', '%B %d, %Y', # 'October 25 2006', 'October 25, 2006'
  323. '%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006'
  324. ``DateTimeField``
  325. ~~~~~~~~~~~~~~~~~
  326. .. class:: DateTimeField(**kwargs)
  327. * Default widget: ``DateTimeInput``
  328. * Empty value: ``None``
  329. * Normalizes to: A Python ``datetime.datetime`` object.
  330. * Validates that the given value is either a ``datetime.datetime``,
  331. ``datetime.date`` or string formatted in a particular datetime format.
  332. * Error message keys: ``required``, ``invalid``
  333. Takes one optional argument:
  334. .. attribute:: DateTimeField.input_formats
  335. A list of formats used to attempt to convert a string to a valid
  336. ``datetime.datetime`` object.
  337. If no ``input_formats`` argument is provided, the default input formats are::
  338. '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59'
  339. '%Y-%m-%d %H:%M', # '2006-10-25 14:30'
  340. '%Y-%m-%d', # '2006-10-25'
  341. '%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59'
  342. '%m/%d/%Y %H:%M', # '10/25/2006 14:30'
  343. '%m/%d/%Y', # '10/25/2006'
  344. '%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59'
  345. '%m/%d/%y %H:%M', # '10/25/06 14:30'
  346. '%m/%d/%y', # '10/25/06'
  347. .. versionchanged:: 1.0
  348. The ``DateTimeField`` used to use a ``TextInput`` widget by default. This has now changed.
  349. ``DecimalField``
  350. ~~~~~~~~~~~~~~~~
  351. .. versionadded:: 1.0
  352. .. class:: DecimalField(**kwargs)
  353. * Default widget: ``TextInput``
  354. * Empty value: ``None``
  355. * Normalizes to: A Python ``decimal``.
  356. * Validates that the given value is a decimal. Leading and trailing
  357. whitespace is ignored.
  358. * Error message keys: ``required``, ``invalid``, ``max_value``,
  359. ``min_value``, ``max_digits``, ``max_decimal_places``,
  360. ``max_whole_digits``
  361. Takes four optional arguments:
  362. .. attribute:: DecimalField.max_value
  363. .. attribute:: DecimalField.min_value
  364. These attributes define the limits for the fields value.
  365. .. attribute:: DecimalField.max_digits
  366. The maximum number of digits (those before the decimal point plus those
  367. after the decimal point, with leading zeros stripped) permitted in the
  368. value.
  369. .. attribute:: DecimalField.decimal_places
  370. The maximum number of decimal places permitted.
  371. ``EmailField``
  372. ~~~~~~~~~~~~~~
  373. .. class:: EmailField(**kwargs)
  374. * Default widget: ``TextInput``
  375. * Empty value: ``''`` (an empty string)
  376. * Normalizes to: A Unicode object.
  377. * Validates that the given value is a valid e-mail address, using a
  378. moderately complex regular expression.
  379. * Error message keys: ``required``, ``invalid``
  380. Has two optional arguments for validation, ``max_length`` and ``min_length``.
  381. If provided, these arguments ensure that the string is at most or at least the
  382. given length.
  383. ``FileField``
  384. ~~~~~~~~~~~~~
  385. .. versionadded:: 1.0
  386. .. class:: FileField(**kwargs)
  387. * Default widget: ``FileInput``
  388. * Empty value: ``None``
  389. * Normalizes to: An ``UploadedFile`` object that wraps the file content
  390. and file name into a single object.
  391. * Validates that non-empty file data has been bound to the form.
  392. * Error message keys: ``required``, ``invalid``, ``missing``, ``empty``
  393. To learn more about the ``UploadedFile`` object, see the :ref:`file uploads
  394. documentation <topics-file-uploads>`.
  395. When you use a ``FileField`` in a form, you must also remember to
  396. :ref:`bind the file data to the form <topics-file-uploads>`.
  397. ``FilePathField``
  398. ~~~~~~~~~~~~~~~~~
  399. .. versionadded:: 1.0
  400. .. class:: FilePathField(**kwargs)
  401. * Default widget: ``Select``
  402. * Empty value: ``None``
  403. * Normalizes to: A unicode object
  404. * Validates that the selected choice exists in the list of choices.
  405. * Error message keys: ``required``, ``invalid_choice``
  406. The field allows choosing from files inside a certain directory. It takes three
  407. extra arguments; only ``path`` is required:
  408. .. attribute:: FilePathField.path
  409. The absolute path to the directory whose contents you want listed. This
  410. directory must exist.
  411. .. attribute:: FilePathField.recursive
  412. If ``False`` (the default) only the direct contents of ``path`` will be
  413. offered as choices. If ``True``, the directory will be descended into
  414. recursively and all descendants will be listed as choices.
  415. .. attribute:: FilePathField.match
  416. A regular expression pattern; only files with names matching this expression
  417. will be allowed as choices.
  418. ``FloatField``
  419. ~~~~~~~~~~~~~~
  420. * Default widget: ``TextInput``
  421. * Empty value: ``None``
  422. * Normalizes to: A Python float.
  423. * Validates that the given value is an float. Leading and trailing
  424. whitespace is allowed, as in Python's ``float()`` function.
  425. * Error message keys: ``required``, ``invalid``, ``max_value``,
  426. ``min_value``
  427. Takes two optional arguments for validation, ``max_value`` and ``min_value``.
  428. These control the range of values permitted in the field.
  429. ``ImageField``
  430. ~~~~~~~~~~~~~~
  431. .. versionadded:: 1.0
  432. .. class:: ImageField(**kwargs)
  433. * Default widget: ``FileInput``
  434. * Empty value: ``None``
  435. * Normalizes to: An ``UploadedFile`` object that wraps the file content
  436. and file name into a single object.
  437. * Validates that file data has been bound to the form, and that the
  438. file is of an image format understood by PIL.
  439. * Error message keys: ``required``, ``invalid``, ``missing``, ``empty``,
  440. ``invalid_image``
  441. Using an ImageField requires that the `Python Imaging Library`_ is installed.
  442. When you use an ``ImageField`` on a form, you must also remember to
  443. :ref:`bind the file data to the form <topics-file-uploads>`.
  444. .. _Python Imaging Library: http://www.pythonware.com/products/pil/
  445. ``IntegerField``
  446. ~~~~~~~~~~~~~~~~
  447. .. class:: IntegerField(**kwargs)
  448. * Default widget: ``TextInput``
  449. * Empty value: ``None``
  450. * Normalizes to: A Python integer or long integer.
  451. * Validates that the given value is an integer. Leading and trailing
  452. whitespace is allowed, as in Python's ``int()`` function.
  453. * Error message keys: ``required``, ``invalid``, ``max_value``,
  454. ``min_value``
  455. Takes two optional arguments for validation:
  456. .. attribute:: IntegerField.max_value
  457. .. attribute:: IntegerField.min_value
  458. These control the range of values permitted in the field.
  459. ``IPAddressField``
  460. ~~~~~~~~~~~~~~~~~~
  461. .. class:: IPAddressField(**kwargs)
  462. * Default widget: ``TextInput``
  463. * Empty value: ``''`` (an empty string)
  464. * Normalizes to: A Unicode object.
  465. * Validates that the given value is a valid IPv4 address, using a regular
  466. expression.
  467. * Error message keys: ``required``, ``invalid``
  468. ``MultipleChoiceField``
  469. ~~~~~~~~~~~~~~~~~~~~~~~
  470. .. class:: MultipleChoiceField(**kwargs)
  471. * Default widget: ``SelectMultiple``
  472. * Empty value: ``[]`` (an empty list)
  473. * Normalizes to: A list of Unicode objects.
  474. * Validates that every value in the given list of values exists in the list
  475. of choices.
  476. * Error message keys: ``required``, ``invalid_choice``, ``invalid_list``
  477. Takes one extra argument, ``choices``, as for ``ChoiceField``.
  478. ``NullBooleanField``
  479. ~~~~~~~~~~~~~~~~~~~~
  480. .. class:: NullBooleanField(**kwargs)
  481. * Default widget: ``NullBooleanSelect``
  482. * Empty value: ``None``
  483. * Normalizes to: A Python ``True``, ``False`` or ``None`` value.
  484. * Validates nothing (i.e., it never raises a ``ValidationError``).
  485. ``RegexField``
  486. ~~~~~~~~~~~~~~
  487. .. class:: RegexField(**kwargs)
  488. * Default widget: ``TextInput``
  489. * Empty value: ``''`` (an empty string)
  490. * Normalizes to: A Unicode object.
  491. * Validates that the given value matches against a certain regular
  492. expression.
  493. * Error message keys: ``required``, ``invalid``
  494. Takes one required argument:
  495. .. attribute:: RegexField.regex
  496. A regular expression specified either as a string or a compiled regular
  497. expression object.
  498. Also takes ``max_length`` and ``min_length``, which work just as they do for
  499. ``CharField``.
  500. The optional argument ``error_message`` is also accepted for backwards
  501. compatibility. The preferred way to provide an error message is to use the
  502. ``error_messages`` argument, passing a dictionary with ``'invalid'`` as a key
  503. and the error message as the value.
  504. ``TimeField``
  505. ~~~~~~~~~~~~~
  506. .. class:: TimeField(**kwargs)
  507. * Default widget: ``TextInput``
  508. * Empty value: ``None``
  509. * Normalizes to: A Python ``datetime.time`` object.
  510. * Validates that the given value is either a ``datetime.time`` or string
  511. formatted in a particular time format.
  512. * Error message keys: ``required``, ``invalid``
  513. Takes one optional argument:
  514. .. attribute:: TimeField.input_formats
  515. A list of formats used to attempt to convert a string to a valid
  516. ``datetime.time`` object.
  517. If no ``input_formats`` argument is provided, the default input formats are::
  518. '%H:%M:%S', # '14:30:59'
  519. '%H:%M', # '14:30'
  520. ``URLField``
  521. ~~~~~~~~~~~~
  522. .. class:: URLField(**kwargs)
  523. * Default widget: ``TextInput``
  524. * Empty value: ``''`` (an empty string)
  525. * Normalizes to: A Unicode object.
  526. * Validates that the given value is a valid URL.
  527. * Error message keys: ``required``, ``invalid``, ``invalid_link``
  528. Takes the following optional arguments:
  529. .. attribute:: URLField.max_length
  530. .. attribute:: URLField.min_length
  531. Same as ``CharField.max_length`` and ``CharField.min_length``.
  532. .. attribute:: URLField.verify_exists
  533. If ``True``, the validator will attempt to load the given URL, raising
  534. ``ValidationError`` if the page gives a 404. Defaults to ``False``.
  535. .. attribute:: URLField.validator_user_agent
  536. String used as the user-agent used when checking for a URL's existence.
  537. Defaults to the value of the ``URL_VALIDATOR_USER_AGENT`` setting.
  538. Slightly complex built-in ``Field`` classes
  539. -------------------------------------------
  540. The following are not yet documented.
  541. .. class:: ComboField(**kwargs)
  542. .. class:: MultiValueField(**kwargs)
  543. .. class:: SplitDateTimeField(**kwargs)
  544. Fields which handle relationships
  545. ---------------------------------
  546. For representing relationships between models, two fields are
  547. provided which can derive their choices from a ``QuerySet``:
  548. .. class:: ModelChoiceField(**kwargs)
  549. .. class:: ModelMultipleChoiceField(**kwargs)
  550. These fields place one or more model objects into the ``cleaned_data``
  551. dictionary of forms in which they're used. Both of these fields have an
  552. additional required argument:
  553. .. attribute:: ModelChoiceField.queryset
  554. A ``QuerySet`` of model objects from which the choices for the
  555. field will be derived, and which will be used to validate the
  556. user's selection.
  557. ``ModelChoiceField``
  558. ~~~~~~~~~~~~~~~~~~~~
  559. Allows the selection of a single model object, suitable for
  560. representing a foreign key.
  561. The ``__unicode__`` method of the model will be called to generate
  562. string representations of the objects for use in the field's choices;
  563. to provide customized representations, subclass ``ModelChoiceField``
  564. and override ``label_from_instance``. This method will receive a model
  565. object, and should return a string suitable for representing it. For
  566. example::
  567. class MyModelChoiceField(ModelChoiceField):
  568. def label_from_instance(self, obj):
  569. return "My Object #%i" % obj.id
  570. ``ModelMultipleChoiceField``
  571. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  572. Allows the selection of one or more model objects, suitable for
  573. representing a many-to-many relation. As with ``ModelChoiceField``,
  574. you can use ``label_from_instance`` to customize the object
  575. representations.
  576. Creating custom fields
  577. ----------------------
  578. If the built-in ``Field`` classes don't meet your needs, you can easily create
  579. custom ``Field`` classes. To do this, just create a subclass of
  580. ``django.forms.Field``. Its only requirements are that it implement a
  581. ``clean()`` method and that its ``__init__()`` method accept the core arguments
  582. mentioned above (``required``, ``label``, ``initial``, ``widget``,
  583. ``help_text``).