fields.txt 27 KB

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