~ubuntu-branches/ubuntu/quantal/python-django/quantal

« back to all changes in this revision

Viewing changes to docs/ref/forms/fields.txt

  • Committer: Bazaar Package Importer
  • Author(s): Chris Lamb
  • Date: 2009-07-29 11:26:28 UTC
  • mfrom: (1.1.8 upstream) (4.1.5 sid)
  • Revision ID: james.westby@ubuntu.com-20090729112628-pg09ino8sz0sj21t
Tags: 1.1-1
* New upstream release.
* Merge from experimental:
  - Ship FastCGI initscript and /etc/default file in python-django's examples
    directory (Closes: #538863)
  - Drop "05_10539-sphinx06-compatibility.diff"; it has been applied
    upstream.
  - Bump Standards-Version to 3.8.2.

Show diffs side-by-side

added added

removed removed

Lines of Context:
23
23
a single argument and either raises a ``django.forms.ValidationError``
24
24
exception or returns the clean value::
25
25
 
 
26
    >>> from django import forms
26
27
    >>> f = forms.EmailField()
27
28
    >>> f.clean('foo@example.com')
28
29
    u'foo@example.com'
126
127
The ``initial`` argument lets you specify the initial value to use when
127
128
rendering this ``Field`` in an unbound ``Form``.
128
129
 
 
130
To specify dynamic initial data, see the :attr:`Form.initial` parameter.
 
131
 
129
132
The use-case for this is when you want to display an "empty" form in which a
130
133
field is initialized to a particular value. For example::
131
134
 
173
176
    >>> f.errors
174
177
    {'url': [u'This field is required.'], 'name': [u'This field is required.']}
175
178
 
 
179
Instead of a constant, you can also pass any callable::
 
180
 
 
181
    >>> import datetime
 
182
    >>> class DateForm(forms.Form):
 
183
    ...     day = forms.DateField(initial=datetime.date.today)
 
184
    >>> print DateForm()
 
185
    <tr><th>Day:</th><td><input type="text" name="day" value="12/23/2008" /><td></tr>
 
186
 
 
187
The callable will be evaluated only when the unbound form is displayed, not when it is defined.
 
188
 
176
189
``widget``
177
190
~~~~~~~~~~
178
191
 
223
236
 
224
237
.. attribute:: Field.error_messages
225
238
 
226
 
 
227
239
The ``error_messages`` argument lets you override the default messages that the
228
240
field will raise. Pass in a dictionary with keys matching the error messages you
229
241
want to override. For example, here is the default error message::
245
257
In the `built-in Field classes`_ section below, each ``Field`` defines the
246
258
error message keys it uses.
247
259
 
248
 
Dynamic initial values
249
 
----------------------
250
 
 
251
 
The ``initial`` argument to ``Field`` (explained above) lets you hard-code the
252
 
initial value for a ``Field`` -- but what if you want to declare the initial
253
 
value at runtime? For example, you might want to fill in a ``username`` field
254
 
with the username of the current session.
255
 
 
256
 
To accomplish this, use the ``initial`` argument to a ``Form``. This argument,
257
 
if given, should be a dictionary mapping field names to initial values. Only
258
 
include the fields for which you're specifying an initial value; it's not
259
 
necessary to include every field in your form. For example::
260
 
 
261
 
    >>> class CommentForm(forms.Form):
262
 
    ...     name = forms.CharField()
263
 
    ...     url = forms.URLField()
264
 
    ...     comment = forms.CharField()
265
 
    >>> f = CommentForm(initial={'name': 'your username'}, auto_id=False)
266
 
    >>> print f
267
 
    <tr><th>Name:</th><td><input type="text" name="name" value="your username" /></td></tr>
268
 
    <tr><th>Url:</th><td><input type="text" name="url" /></td></tr>
269
 
    <tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr>
270
 
    >>> f = CommentForm(initial={'name': 'another username'}, auto_id=False)
271
 
    >>> print f
272
 
    <tr><th>Name:</th><td><input type="text" name="name" value="another username" /></td></tr>
273
 
    <tr><th>Url:</th><td><input type="text" name="url" /></td></tr>
274
 
    <tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr>
275
 
 
276
 
Just like the ``initial`` parameter to ``Field``, these values are only
277
 
displayed for unbound forms, and they're not used as fallback values if a
278
 
particular value isn't provided.
279
 
 
280
 
Finally, note that if a ``Field`` defines ``initial`` *and* you include
281
 
``initial`` when instantiating the ``Form``, then the latter ``initial`` will
282
 
have precedence. In this example, ``initial`` is provided both at the field
283
 
level and at the form instance level, and the latter gets precedence::
284
 
 
285
 
    >>> class CommentForm(forms.Form):
286
 
    ...     name = forms.CharField(initial='class')
287
 
    ...     url = forms.URLField()
288
 
    ...     comment = forms.CharField()
289
 
    >>> f = CommentForm(initial={'name': 'instance'}, auto_id=False)
290
 
    >>> print f
291
 
    <tr><th>Name:</th><td><input type="text" name="name" value="instance" /></td></tr>
292
 
    <tr><th>Url:</th><td><input type="text" name="url" /></td></tr>
293
 
    <tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr>
294
 
 
295
 
 
296
260
Built-in ``Field`` classes
297
261
--------------------------
298
262
 
311
275
    * Default widget: ``CheckboxInput``
312
276
    * Empty value: ``False``
313
277
    * Normalizes to: A Python ``True`` or ``False`` value.
314
 
    * Validates that the check box is checked (i.e. the value is ``True``) if
 
278
    * Validates that the value is ``True`` (e.g. the check box is checked) if
315
279
      the field has ``required=True``.
316
280
    * Error message keys: ``required``
317
281
 
323
287
.. note::
324
288
 
325
289
    Since all ``Field`` subclasses have ``required=True`` by default, the
326
 
    validation condition here is important. If you want to include a checkbox
327
 
    in your form that can be either checked or unchecked, you must remember to
328
 
    pass in ``required=False`` when creating the ``BooleanField``.
 
290
    validation condition here is important. If you want to include a boolean
 
291
    in your form that can be either ``True`` or ``False`` (e.g. a checked or
 
292
    unchecked checkbox), you must remember to pass in ``required=False`` when
 
293
    creating the ``BooleanField``.
329
294
 
330
295
``CharField``
331
296
~~~~~~~~~~~~~
364
329
 
365
330
    An iterable (e.g., a list or tuple) of 2-tuples to use as choices for this
366
331
    field.
367
 
    
 
332
 
368
333
``TypedChoiceField``
369
334
~~~~~~~~~~~~~~~~~~~~
370
335
 
397
362
 
398
363
.. class:: DateField(**kwargs)
399
364
 
400
 
    * Default widget: ``TextInput``
 
365
    * Default widget: ``DateInput``
401
366
    * Empty value: ``None``
402
367
    * Normalizes to: A Python ``datetime.date`` object.
403
368
    * Validates that the given value is either a ``datetime.date``,
419
384
    '%B %d %Y', '%B %d, %Y',            # 'October 25 2006', 'October 25, 2006'
420
385
    '%d %B %Y', '%d %B, %Y',            # '25 October 2006', '25 October, 2006'
421
386
 
 
387
.. versionchanged:: 1.1
 
388
   The ``DateField`` previously used a ``TextInput`` widget by default. It now
 
389
   uses a ``DateInput`` widget.
 
390
 
422
391
``DateTimeField``
423
392
~~~~~~~~~~~~~~~~~
424
393
 
469
438
      ``min_value``, ``max_digits``, ``max_decimal_places``,
470
439
      ``max_whole_digits``
471
440
 
472
 
Takes four optional arguments: 
 
441
Takes four optional arguments:
473
442
 
474
443
.. attribute:: DecimalField.max_value
475
444
.. attribute:: DecimalField.min_value
481
450
    The maximum number of digits (those before the decimal point plus those
482
451
    after the decimal point, with leading zeros stripped) permitted in the
483
452
    value.
484
 
    
 
453
 
485
454
.. attribute:: DecimalField.decimal_places
486
455
 
487
456
    The maximum number of decimal places permitted.
517
486
    * Error message keys: ``required``, ``invalid``, ``missing``, ``empty``
518
487
 
519
488
To learn more about the ``UploadedFile`` object, see the :ref:`file uploads
520
 
documentation <topics-file-uploads>`.
 
489
documentation <topics-http-file-uploads>`.
521
490
 
522
491
When you use a ``FileField`` in a form, you must also remember to
523
 
:ref:`bind the file data to the form <topics-file-uploads>`.
 
492
:ref:`bind the file data to the form <binding-uploaded-files>`.
524
493
 
525
494
``FilePathField``
526
495
~~~~~~~~~~~~~~~~~
554
523
    A regular expression pattern; only files with names matching this expression
555
524
    will be allowed as choices.
556
525
 
557
 
``FloatField`` 
558
 
~~~~~~~~~~~~~~ 
559
 
 
560
 
    * Default widget: ``TextInput`` 
561
 
    * Empty value: ``None`` 
562
 
    * Normalizes to: A Python float. 
563
 
    * Validates that the given value is an float. Leading and trailing 
564
 
      whitespace is allowed, as in Python's ``float()`` function. 
565
 
    * Error message keys: ``required``, ``invalid``, ``max_value``, 
566
 
      ``min_value`` 
567
 
         
568
 
Takes two optional arguments for validation, ``max_value`` and ``min_value``. 
 
526
``FloatField``
 
527
~~~~~~~~~~~~~~
 
528
 
 
529
    * Default widget: ``TextInput``
 
530
    * Empty value: ``None``
 
531
    * Normalizes to: A Python float.
 
532
    * Validates that the given value is an float. Leading and trailing
 
533
      whitespace is allowed, as in Python's ``float()`` function.
 
534
    * Error message keys: ``required``, ``invalid``, ``max_value``,
 
535
      ``min_value``
 
536
 
 
537
Takes two optional arguments for validation, ``max_value`` and ``min_value``.
569
538
These control the range of values permitted in the field.
570
539
 
571
540
``ImageField``
587
556
Using an ImageField requires that the `Python Imaging Library`_ is installed.
588
557
 
589
558
When you use an ``ImageField`` on a form, you must also remember to
590
 
:ref:`bind the file data to the form <topics-file-uploads>`.
 
559
:ref:`bind the file data to the form <binding-uploaded-files>`.
591
560
 
592
561
.. _Python Imaging Library: http://www.pythonware.com/products/pil/
593
562
 
738
707
 
739
708
.. class:: SplitDateTimeField(**kwargs)
740
709
 
 
710
    * Default widget: ``SplitDateTimeWidget``
 
711
    * Empty value: ``None``
 
712
    * Normalizes to: A Python ``datetime.datetime`` object.
 
713
    * Validates that the given value is a ``datetime.datetime`` or string
 
714
      formatted in a particular datetime format.
 
715
    * Error message keys: ``required``, ``invalid``
 
716
 
 
717
Takes two optional arguments:
 
718
 
 
719
.. attribute:: SplitDateTimeField.input_date_formats
 
720
 
 
721
    A list of formats used to attempt to convert a string to a valid
 
722
    ``datetime.date`` object.
 
723
 
 
724
If no ``input_date_formats`` argument is provided, the default input formats
 
725
for ``DateField`` are used.
 
726
 
 
727
.. attribute:: SplitDateTimeField.input_time_formats
 
728
 
 
729
    A list of formats used to attempt to convert a string to a valid
 
730
    ``datetime.time`` object.
 
731
 
 
732
If no ``input_time_formats`` argument is provided, the default input formats
 
733
for ``TimeField`` are used.
 
734
 
 
735
.. versionchanged:: 1.1
 
736
   The ``SplitDateTimeField`` previously used two ``TextInput`` widgets by
 
737
   default. The ``input_date_formats`` and ``input_time_formats`` arguments
 
738
   are also new.
 
739
 
741
740
Fields which handle relationships
742
741
---------------------------------
743
742
 
774
773
        def label_from_instance(self, obj):
775
774
            return "My Object #%i" % obj.id
776
775
 
 
776
.. attribute:: ModelChoiceField.empty_label
 
777
 
 
778
   By default the ``<select>`` widget used by ``ModelChoiceField`` will have a
 
779
   an empty choice at the top of the list. You can change the text of this label
 
780
   (which is ``"---------"`` by default) with the ``empty_label`` attribute, or
 
781
   you can disable the empty label entirely by setting ``empty_label`` to
 
782
   ``None``::
 
783
 
 
784
        # A custom empty label
 
785
        field1 = forms.ModelChoiceField(queryset=..., empty_label="(Nothing)")
 
786
 
 
787
        # No empty label
 
788
        field2 = forms.ModelChoiceField(queryset=..., empty_label=None)
 
789
 
 
790
   Note that if a ``ModelChoiceField`` is required and has a default
 
791
   initial value, no empty choice is created (regardless of the value
 
792
   of ``empty_label``).
 
793
 
777
794
``ModelMultipleChoiceField``
778
795
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
779
796