PageRenderTime 211ms CodeModel.GetById 101ms app.highlight 6ms RepoModel.GetById 84ms app.codeStats 0ms

/docs/ref/forms/fields.txt

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