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