summaryrefslogtreecommitdiff
path: root/docs/ref/forms/fields.txt
blob: 4084ae78d5d8c00978729d749e7476de7e697c30 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
===========
Form fields
===========

.. module:: django.forms.fields
   :synopsis: Django's built-in form fields.

.. currentmodule:: django.forms

.. class:: Field(**kwargs)

When you create a ``Form`` class, the most important part is defining the
fields of the form. Each field has custom validation logic, along with a few
other hooks.

.. method:: Field.clean(value)

Although the primary way you'll use ``Field`` classes is in ``Form`` classes,
you can also instantiate them and use them directly to get a better idea of
how they work. Each ``Field`` instance has a ``clean()`` method, which takes
a single argument and either raises a
``django.core.exceptions.ValidationError`` exception or returns the clean
value:

.. code-block:: pycon

    >>> from django import forms
    >>> f = forms.EmailField()
    >>> f.clean("foo@example.com")
    'foo@example.com'
    >>> f.clean("invalid email address")
    Traceback (most recent call last):
    ...
    ValidationError: ['Enter a valid email address.']

.. _core-field-arguments:

Core field arguments
====================

Each ``Field`` class constructor takes at least these arguments. Some
``Field`` classes take additional, field-specific arguments, but the following
should *always* be accepted:

``required``
------------

.. attribute:: Field.required

By default, each ``Field`` class assumes the value is required, so if you pass
an empty value -- either ``None`` or the empty string (``""``) -- then
``clean()`` will raise a ``ValidationError`` exception:

.. code-block:: pycon

    >>> from django import forms
    >>> f = forms.CharField()
    >>> f.clean("foo")
    'foo'
    >>> f.clean("")
    Traceback (most recent call last):
    ...
    ValidationError: ['This field is required.']
    >>> f.clean(None)
    Traceback (most recent call last):
    ...
    ValidationError: ['This field is required.']
    >>> f.clean(" ")
    ' '
    >>> f.clean(0)
    '0'
    >>> f.clean(True)
    'True'
    >>> f.clean(False)
    'False'

To specify that a field is *not* required, pass ``required=False`` to the
``Field`` constructor:

.. code-block:: pycon

    >>> f = forms.CharField(required=False)
    >>> f.clean("foo")
    'foo'
    >>> f.clean("")
    ''
    >>> f.clean(None)
    ''
    >>> f.clean(0)
    '0'
    >>> f.clean(True)
    'True'
    >>> f.clean(False)
    'False'

If a ``Field`` has ``required=False`` and you pass ``clean()`` an empty value,
then ``clean()`` will return a *normalized* empty value rather than raising
``ValidationError``. For ``CharField``, this will return
:attr:`~CharField.empty_value` which defaults to an empty string. For other
``Field`` classes, it might be ``None``. (This varies from field to field.)

Widgets of required form fields have the ``required`` HTML attribute. Set the
:attr:`Form.use_required_attribute` attribute to ``False`` to disable it. The
``required`` attribute isn't included on forms of formsets because the browser
validation may not be correct when adding and deleting formsets.

``label``
---------

.. attribute:: Field.label

The ``label`` argument lets you specify the "human-friendly" label for this
field. This is used when the ``Field`` is displayed in a ``Form``.

As explained in "Outputting forms as HTML" above, the default label for a
``Field`` is generated from the field name by converting all underscores to
spaces and upper-casing the first letter. Specify ``label`` if that default
behavior doesn't result in an adequate label.

Here's a full example ``Form`` that implements ``label`` for two of its fields.
We've specified ``auto_id=False`` to simplify the output:

.. code-block:: pycon

    >>> from django import forms
    >>> class CommentForm(forms.Form):
    ...     name = forms.CharField(label="Your name")
    ...     url = forms.URLField(label="Your website", required=False)
    ...     comment = forms.CharField()
    ...
    >>> f = CommentForm(auto_id=False)
    >>> print(f)
    <div>Your name:<input type="text" name="name" required></div>
    <div>Your website:<input type="url" name="url"></div>
    <div>Comment:<input type="text" name="comment" required></div>

``label_suffix``
----------------

.. attribute:: Field.label_suffix

The ``label_suffix`` argument lets you override the form's
:attr:`~django.forms.Form.label_suffix` on a per-field basis:

.. code-block:: pycon

    >>> class ContactForm(forms.Form):
    ...     age = forms.IntegerField()
    ...     nationality = forms.CharField()
    ...     captcha_answer = forms.IntegerField(label="2 + 2", label_suffix=" =")
    ...
    >>> f = ContactForm(label_suffix="?")
    >>> print(f)
    <div><label for="id_age">Age?</label><input type="number" name="age" required id="id_age"></div>
    <div><label for="id_nationality">Nationality?</label><input type="text" name="nationality" required id="id_nationality"></div>
    <div><label for="id_captcha_answer">2 + 2 =</label><input type="number" name="captcha_answer" required id="id_captcha_answer"></div>

``initial``
-----------

.. attribute:: Field.initial

The ``initial`` argument lets you specify the initial value to use when
rendering this ``Field`` in an unbound ``Form``.

To specify dynamic initial data, see the :attr:`Form.initial` parameter.

The use-case for this is when you want to display an "empty" form in which a
field is initialized to a particular value. For example:

.. code-block:: pycon

    >>> from django import forms
    >>> class CommentForm(forms.Form):
    ...     name = forms.CharField(initial="Your name")
    ...     url = forms.URLField(initial="http://")
    ...     comment = forms.CharField()
    ...
    >>> f = CommentForm(auto_id=False)
    >>> print(f)
    <div>Name:<input type="text" name="name" value="Your name" required></div>
    <div>Url:<input type="url" name="url" value="http://" required></div>
    <div>Comment:<input type="text" name="comment" required></div>

You may be thinking, why not just pass a dictionary of the initial values as
data when displaying the form? Well, if you do that, you'll trigger validation,
and the HTML output will include any validation errors:

.. code-block:: pycon

    >>> class CommentForm(forms.Form):
    ...     name = forms.CharField()
    ...     url = forms.URLField()
    ...     comment = forms.CharField()
    ...
    >>> default_data = {"name": "Your name", "url": "http://"}
    >>> f = CommentForm(default_data, auto_id=False)
    >>> print(f)
    <div>Name:<input type="text" name="name" value="Your name" required></div>
    <div>Url:<ul class="errorlist"><li>Enter a valid URL.</li></ul><input type="url" name="url" value="http://" required></div>
    <div>Comment:<ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="comment" required></div>

This is why ``initial`` values are only displayed for unbound forms. For bound
forms, the HTML output will use the bound data.

Also note that ``initial`` values are *not* used as "fallback" data in
validation if a particular field's value is not given. ``initial`` values are
*only* intended for initial form display:

.. code-block:: pycon

    >>> class CommentForm(forms.Form):
    ...     name = forms.CharField(initial="Your name")
    ...     url = forms.URLField(initial="http://")
    ...     comment = forms.CharField()
    ...
    >>> data = {"name": "", "url": "", "comment": "Foo"}
    >>> f = CommentForm(data)
    >>> f.is_valid()
    False
    # The form does *not* fall back to using the initial values.
    >>> f.errors
    {'url': ['This field is required.'], 'name': ['This field is required.']}

Instead of a constant, you can also pass any callable:

.. code-block:: pycon

    >>> import datetime
    >>> class DateForm(forms.Form):
    ...     day = forms.DateField(initial=datetime.date.today)
    ...
    >>> print(DateForm())
    <div><label for="id_day">Day:</label><input type="text" name="day" value="2023-02-11" required id="id_day"></div>

The callable will be evaluated only when the unbound form is displayed, not when it is defined.

``widget``
----------

.. attribute:: Field.widget

The ``widget`` argument lets you specify a ``Widget`` class to use when
rendering this ``Field``. See :doc:`/ref/forms/widgets` for more information.

``help_text``
-------------

.. attribute:: Field.help_text

The ``help_text`` argument lets you specify descriptive text for this
``Field``. If you provide ``help_text``, it will be displayed next to the
``Field`` when the ``Field`` is rendered by one of the convenience ``Form``
methods (e.g., ``as_ul()``).

Like the model field's :attr:`~django.db.models.Field.help_text`, this value
isn't HTML-escaped in automatically-generated forms.

Here's a full example ``Form`` that implements ``help_text`` for two of its
fields. We've specified ``auto_id=False`` to simplify the output:

.. code-block:: pycon

    >>> from django import forms
    >>> class HelpTextContactForm(forms.Form):
    ...     subject = forms.CharField(max_length=100, help_text="100 characters max.")
    ...     message = forms.CharField()
    ...     sender = forms.EmailField(help_text="A valid email address, please.")
    ...     cc_myself = forms.BooleanField(required=False)
    ...
    >>> f = HelpTextContactForm(auto_id=False)
    >>> print(f)
    <div>Subject:<div class="helptext">100 characters max.</div><input type="text" name="subject" maxlength="100" required></div>
    <div>Message:<input type="text" name="message" required></div>
    <div>Sender:<div class="helptext">A valid email address, please.</div><input type="email" name="sender" required></div>
    <div>Cc myself:<input type="checkbox" name="cc_myself"></div>

``error_messages``
------------------

.. attribute:: Field.error_messages

The ``error_messages`` argument lets you override the default messages that the
field will raise. Pass in a dictionary with keys matching the error messages you
want to override. For example, here is the default error message:

.. code-block:: pycon

    >>> from django import forms
    >>> generic = forms.CharField()
    >>> generic.clean("")
    Traceback (most recent call last):
      ...
    ValidationError: ['This field is required.']

And here is a custom error message:

.. code-block:: pycon

    >>> name = forms.CharField(error_messages={"required": "Please enter your name"})
    >>> name.clean("")
    Traceback (most recent call last):
      ...
    ValidationError: ['Please enter your name']

In the `built-in Field classes`_ section below, each ``Field`` defines the
error message keys it uses.

``validators``
--------------

.. attribute:: Field.validators

The ``validators`` argument lets you provide a list of validation functions
for this field.

See the :doc:`validators documentation </ref/validators>` for more information.

``localize``
------------

.. attribute:: Field.localize

The ``localize`` argument enables the localization of form data input, as well
as the rendered output.

See the :doc:`format localization </topics/i18n/formatting>` documentation for
more information.

``disabled``
------------

.. attribute:: Field.disabled

The ``disabled`` boolean argument, when set to ``True``, disables a form field
using the ``disabled`` HTML attribute so that it won't be editable by users.
Even if a user tampers with the field's value submitted to the server, it will
be ignored in favor of the value from the form's initial data.

``template_name``
-----------------

.. attribute:: Field.template_name

.. versionadded:: 5.0

The ``template_name`` argument allows a custom template to be used when the
field is rendered with :meth:`~django.forms.BoundField.as_field_group`. By 
default this value is set to ``"django/forms/field.html"``. Can be changed per
field by overriding this attribute or more generally by overriding the default
template, see also :ref:`overriding-built-in-field-templates`.

Checking if the field data has changed
======================================

``has_changed()``
-----------------

.. method:: Field.has_changed()

The ``has_changed()`` method is used to determine if the field value has changed
from the initial value. Returns ``True`` or ``False``.

See the :class:`Form.has_changed()` documentation for more information.

.. _built-in-fields:

Built-in ``Field`` classes
==========================

Naturally, the ``forms`` library comes with a set of ``Field`` classes that
represent common validation needs. This section documents each built-in field.

For each field, we describe the default widget used if you don't specify
``widget``. We also specify the value returned when you provide an empty value
(see the section on ``required`` above to understand what that means).

``BooleanField``
----------------

.. class:: BooleanField(**kwargs)

    * Default widget: :class:`CheckboxInput`
    * Empty value: ``False``
    * Normalizes to: A Python ``True`` or ``False`` value.
    * Validates that the value is ``True`` (e.g. the check box is checked) if
      the field has ``required=True``.
    * Error message keys: ``required``

    .. note::

        Since all ``Field`` subclasses have ``required=True`` by default, the
        validation condition here is important. If you want to include a boolean
        in your form that can be either ``True`` or ``False`` (e.g. a checked or
        unchecked checkbox), you must remember to pass in ``required=False`` when
        creating the ``BooleanField``.

``CharField``
-------------

.. class:: CharField(**kwargs)

    * Default widget: :class:`TextInput`
    * Empty value: Whatever you've given as :attr:`empty_value`.
    * Normalizes to: A string.
    * Uses :class:`~django.core.validators.MaxLengthValidator` and
      :class:`~django.core.validators.MinLengthValidator` if ``max_length`` and
      ``min_length`` are provided. Otherwise, all inputs are valid.
    * Error message keys: ``required``, ``max_length``, ``min_length``

    Has the following optional arguments for validation:

    .. attribute:: max_length
    .. attribute:: min_length

        If provided, these arguments ensure that the string is at most or at
        least the given length.

    .. attribute:: strip

       If ``True`` (default), the value will be stripped of leading and
       trailing whitespace.

    .. attribute:: empty_value

       The value to use to represent "empty". Defaults to an empty string.

``ChoiceField``
---------------

.. class:: ChoiceField(**kwargs)

    * Default widget: :class:`Select`
    * Empty value: ``''`` (an empty string)
    * Normalizes to: A string.
    * Validates that the given value exists in the list of choices.
    * Error message keys: ``required``, ``invalid_choice``

    The ``invalid_choice`` error message may contain ``%(value)s``, which will be
    replaced with the selected choice.

    Takes one extra argument:

    .. attribute:: choices

        Either an :term:`iterable` of 2-tuples to use as choices for this
        field, :ref:`enumeration type <field-choices-enum-types>`, or a
        callable that returns such an iterable. This argument accepts the same
        formats as the ``choices`` argument to a model field. See the
        :ref:`model field reference documentation on choices <field-choices>`
        for more details. If the argument is a callable, it is evaluated each
        time the field's form is initialized, in addition to during rendering.
        Defaults to an empty list.

    .. versionchanged:: 5.0

        Support for using :ref:`enumeration types <field-choices-enum-types>`
        directly in the ``choices`` was added.

``DateField``
-------------

.. class:: DateField(**kwargs)

    * Default widget: :class:`DateInput`
    * Empty value: ``None``
    * Normalizes to: A Python ``datetime.date`` object.
    * Validates that the given value is either a ``datetime.date``,
      ``datetime.datetime`` or string formatted in a particular date format.
    * Error message keys: ``required``, ``invalid``

    Takes one optional argument:

    .. attribute:: input_formats

        An iterable of formats used to attempt to convert a string to a valid
        ``datetime.date`` object.

    If no ``input_formats`` argument is provided, the default input formats are
    taken from the active locale format ``DATE_INPUT_FORMATS`` key, or from
    :setting:`DATE_INPUT_FORMATS` if localization is disabled. See also
    :doc:`format localization </topics/i18n/formatting>`.

``DateTimeField``
-----------------

.. class:: DateTimeField(**kwargs)

    * Default widget: :class:`DateTimeInput`
    * Empty value: ``None``
    * Normalizes to: A Python ``datetime.datetime`` object.
    * Validates that the given value is either a ``datetime.datetime``,
      ``datetime.date`` or string formatted in a particular datetime format.
    * Error message keys: ``required``, ``invalid``

    Takes one optional argument:

    .. attribute:: input_formats

        An iterable of formats used to attempt to convert a string to a valid
        ``datetime.datetime`` object, in addition to ISO 8601 formats.

    The field always accepts strings in ISO 8601 formatted dates or similar
    recognized by :func:`~django.utils.dateparse.parse_datetime`. Some examples
    are:

    * ``'2006-10-25 14:30:59'``
    * ``'2006-10-25T14:30:59'``
    * ``'2006-10-25 14:30'``
    * ``'2006-10-25T14:30'``
    * ``'2006-10-25T14:30Z'``
    * ``'2006-10-25T14:30+02:00'``
    * ``'2006-10-25'``

    If no ``input_formats`` argument is provided, the default input formats are
    taken from the active locale format ``DATETIME_INPUT_FORMATS`` and
    ``DATE_INPUT_FORMATS`` keys, or from :setting:`DATETIME_INPUT_FORMATS` and
    :setting:`DATE_INPUT_FORMATS` if localization is disabled. See also
    :doc:`format localization </topics/i18n/formatting>`.

``DecimalField``
----------------

.. class:: DecimalField(**kwargs)

    * Default widget: :class:`NumberInput` when :attr:`Field.localize` is
      ``False``, else :class:`TextInput`.
    * Empty value: ``None``
    * Normalizes to: A Python ``decimal``.
    * Validates that the given value is a decimal. Uses
      :class:`~django.core.validators.MaxValueValidator` and
      :class:`~django.core.validators.MinValueValidator` if ``max_value`` and
      ``min_value`` are provided. Uses
      :class:`~django.core.validators.StepValueValidator` if ``step_size`` is
      provided. Leading and trailing whitespace is ignored.
    * Error message keys: ``required``, ``invalid``, ``max_value``,
      ``min_value``, ``max_digits``, ``max_decimal_places``,
      ``max_whole_digits``, ``step_size``.

    The ``max_value`` and ``min_value`` error messages may contain
    ``%(limit_value)s``, which will be substituted by the appropriate limit.
    Similarly, the ``max_digits``, ``max_decimal_places`` and
    ``max_whole_digits`` error messages may contain ``%(max)s``.

    Takes five optional arguments:

    .. attribute:: max_value
    .. attribute:: min_value

        These control the range of values permitted in the field, and should be
        given as ``decimal.Decimal`` values.

    .. attribute:: max_digits

        The maximum number of digits (those before the decimal point plus those
        after the decimal point, with leading zeros stripped) permitted in the
        value.

    .. attribute:: decimal_places

        The maximum number of decimal places permitted.

    .. attribute:: step_size

        Limit valid inputs to an integral multiple of ``step_size``.

``DurationField``
-----------------

.. class:: DurationField(**kwargs)

    * Default widget: :class:`TextInput`
    * Empty value: ``None``
    * Normalizes to: A Python :class:`~python:datetime.timedelta`.
    * Validates that the given value is a string which can be converted into a
      ``timedelta``. The value must be between :attr:`datetime.timedelta.min`
      and :attr:`datetime.timedelta.max`.
    * Error message keys: ``required``, ``invalid``, ``overflow``.

    Accepts any format understood by
    :func:`~django.utils.dateparse.parse_duration`.

``EmailField``
--------------

.. class:: EmailField(**kwargs)

    * Default widget: :class:`EmailInput`
    * Empty value: Whatever you've given as ``empty_value``.
    * Normalizes to: A string.
    * Uses :class:`~django.core.validators.EmailValidator` to validate that
      the given value is a valid email address, using a moderately complex
      regular expression.
    * Error message keys: ``required``, ``invalid``

    Has the optional arguments ``max_length``, ``min_length``, and
    ``empty_value`` which work just as they do for :class:`CharField`.

``FileField``
-------------

.. class:: FileField(**kwargs)

    * Default widget: :class:`ClearableFileInput`
    * Empty value: ``None``
    * Normalizes to: An ``UploadedFile`` object that wraps the file content
      and file name into a single object.
    * Can validate that non-empty file data has been bound to the form.
    * Error message keys: ``required``, ``invalid``, ``missing``, ``empty``,
      ``max_length``

    Has the optional arguments for validation: ``max_length`` and
    ``allow_empty_file``. If provided, these ensure that the file name is at
    most the given length, and that validation will succeed even if the file
    content is empty.

    To learn more about the ``UploadedFile`` object, see the :doc:`file uploads
    documentation </topics/http/file-uploads>`.

    When you use a ``FileField`` in a form, you must also remember to
    :ref:`bind the file data to the form <binding-uploaded-files>`.

    The ``max_length`` error refers to the length of the filename. In the error
    message for that key, ``%(max)d`` will be replaced with the maximum filename
    length and ``%(length)d`` will be replaced with the current filename length.

``FilePathField``
-----------------

.. class:: FilePathField(**kwargs)

    * Default widget: :class:`Select`
    * Empty value: ``''`` (an empty string)
    * Normalizes to: A string.
    * Validates that the selected choice exists in the list of choices.
    * Error message keys: ``required``, ``invalid_choice``

    The field allows choosing from files inside a certain directory. It takes five
    extra arguments; only ``path`` is required:

    .. attribute:: path

        The absolute path to the directory whose contents you want listed. This
        directory must exist.

    .. attribute:: recursive

        If ``False`` (the default) only the direct contents of ``path`` will be
        offered as choices. If ``True``, the directory will be descended into
        recursively and all descendants will be listed as choices.

    .. attribute:: match

        A regular expression pattern; only files with names matching this expression
        will be allowed as choices.

    .. attribute:: allow_files

        Optional.  Either ``True`` or ``False``.  Default is ``True``.  Specifies
        whether files in the specified location should be included.  Either this or
        :attr:`allow_folders` must be ``True``.

    .. attribute:: allow_folders

        Optional.  Either ``True`` or ``False``.  Default is ``False``.  Specifies
        whether folders in the specified location should be included.  Either this or
        :attr:`allow_files` must be ``True``.


``FloatField``
--------------

.. class:: FloatField(**kwargs)

    * Default widget: :class:`NumberInput` when :attr:`Field.localize` is
      ``False``, else :class:`TextInput`.
    * Empty value: ``None``
    * Normalizes to: A Python float.
    * Validates that the given value is a float. Uses
      :class:`~django.core.validators.MaxValueValidator` and
      :class:`~django.core.validators.MinValueValidator` if ``max_value`` and
      ``min_value`` are provided. Uses
      :class:`~django.core.validators.StepValueValidator` if ``step_size`` is
      provided. Leading and trailing whitespace is allowed, as in Python's
      ``float()`` function.
    * Error message keys: ``required``, ``invalid``, ``max_value``,
      ``min_value``, ``step_size``.

    Takes three optional arguments:

    .. attribute:: max_value
    .. attribute:: min_value

        These control the range of values permitted in the field.

    .. attribute:: step_size

        Limit valid inputs to an integral multiple of ``step_size``.

``GenericIPAddressField``
-------------------------

.. class:: GenericIPAddressField(**kwargs)

    A field containing either an IPv4 or an IPv6 address.

    * Default widget: :class:`TextInput`
    * Empty value: ``''`` (an empty string)
    * Normalizes to: A string. IPv6 addresses are normalized as described below.
    * Validates that the given value is a valid IP address.
    * Error message keys: ``required``, ``invalid``

    The IPv6 address normalization follows :rfc:`4291#section-2.2` section 2.2,
    including using the IPv4 format suggested in paragraph 3 of that section, like
    ``::ffff:192.0.2.0``. For example, ``2001:0::0:01`` would be normalized to
    ``2001::1``, and ``::ffff:0a0a:0a0a`` to ``::ffff:10.10.10.10``. All characters
    are converted to lowercase.

    Takes two optional arguments:

    .. attribute:: protocol

        Limits valid inputs to the specified protocol.
        Accepted values are ``both`` (default), ``IPv4``
        or ``IPv6``. Matching is case insensitive.

    .. attribute:: unpack_ipv4

        Unpacks IPv4 mapped addresses like ``::ffff:192.0.2.1``.
        If this option is enabled that address would be unpacked to
        ``192.0.2.1``. Default is disabled. Can only be used
        when ``protocol`` is set to ``'both'``.

``ImageField``
--------------

.. class:: ImageField(**kwargs)

    * Default widget: :class:`ClearableFileInput`
    * Empty value: ``None``
    * Normalizes to: An ``UploadedFile`` object that wraps the file content
      and file name into a single object.
    * Validates that file data has been bound to the form. Also uses
      :class:`~django.core.validators.FileExtensionValidator` to validate that
      the file extension is supported by Pillow.
    * Error message keys: ``required``, ``invalid``, ``missing``, ``empty``,
      ``invalid_image``

    Using an ``ImageField`` requires that `Pillow`_ is installed with support
    for the image formats you use. If you encounter a ``corrupt image`` error
    when you upload an image, it usually means that Pillow doesn't understand
    its format. To fix this, install the appropriate library and reinstall
    Pillow.

    When you use an ``ImageField`` on a form, you must also remember to
    :ref:`bind the file data to the form <binding-uploaded-files>`.

    After the field has been cleaned and validated, the ``UploadedFile``
    object will have an additional ``image`` attribute containing the Pillow
    `Image`_ instance used to check if the file was a valid image. Pillow
    closes the underlying file descriptor after verifying an image, so while
    non-image data attributes, such as ``format``, ``height``, and ``width``,
    are available, methods that access the underlying image data, such as
    ``getdata()`` or ``getpixel()``, cannot be used without reopening the file.
    For example:

    .. code-block:: pycon

        >>> from PIL import Image
        >>> from django import forms
        >>> from django.core.files.uploadedfile import SimpleUploadedFile
        >>> class ImageForm(forms.Form):
        ...     img = forms.ImageField()
        ...
        >>> file_data = {"img": SimpleUploadedFile("test.png", b"file data")}
        >>> form = ImageForm({}, file_data)
        # Pillow closes the underlying file descriptor.
        >>> form.is_valid()
        True
        >>> image_field = form.cleaned_data["img"]
        >>> image_field.image
        <PIL.PngImagePlugin.PngImageFile image mode=RGBA size=191x287 at 0x7F5985045C18>
        >>> image_field.image.width
        191
        >>> image_field.image.height
        287
        >>> image_field.image.format
        'PNG'
        >>> image_field.image.getdata()
        # Raises AttributeError: 'NoneType' object has no attribute 'seek'.
        >>> image = Image.open(image_field)
        >>> image.getdata()
        <ImagingCore object at 0x7f5984f874b0>

    Additionally, ``UploadedFile.content_type`` will be updated with the
    image's content type if Pillow can determine it, otherwise it will be set
    to ``None``.

.. _Pillow: https://pillow.readthedocs.io/en/latest/
.. _Image: https://pillow.readthedocs.io/en/latest/reference/Image.html

``IntegerField``
----------------

.. class:: IntegerField(**kwargs)

    * Default widget: :class:`NumberInput` when :attr:`Field.localize` is
      ``False``, else :class:`TextInput`.
    * Empty value: ``None``
    * Normalizes to: A Python integer.
    * Validates that the given value is an integer. Uses
      :class:`~django.core.validators.MaxValueValidator` and
      :class:`~django.core.validators.MinValueValidator` if ``max_value`` and
      ``min_value`` are provided. Uses
      :class:`~django.core.validators.StepValueValidator` if ``step_size`` is
      provided. Leading and trailing whitespace is allowed, as in Python's
      ``int()`` function.
    * Error message keys: ``required``, ``invalid``, ``max_value``,
      ``min_value``, ``step_size``

    The ``max_value``, ``min_value`` and ``step_size`` error messages may
    contain ``%(limit_value)s``, which will be substituted by the appropriate
    limit.

    Takes three optional arguments for validation:

    .. attribute:: max_value
    .. attribute:: min_value

        These control the range of values permitted in the field.

    .. attribute:: step_size

        Limit valid inputs to an integral multiple of ``step_size``.

``JSONField``
-------------

.. class:: JSONField(encoder=None, decoder=None, **kwargs)

    A field which accepts JSON encoded data for a
    :class:`~django.db.models.JSONField`.

    * Default widget: :class:`Textarea`
    * Empty value: ``None``
    * Normalizes to: A Python representation of the JSON value (usually as a
      ``dict``, ``list``, or ``None``), depending on :attr:`JSONField.decoder`.
    * Validates that the given value is a valid JSON.
    * Error message keys: ``required``, ``invalid``

    Takes two optional arguments:

    .. attribute:: encoder

        A :py:class:`json.JSONEncoder` subclass to serialize data types not
        supported by the standard JSON serializer (e.g. ``datetime.datetime``
        or :class:`~python:uuid.UUID`). For example, you can use the
        :class:`~django.core.serializers.json.DjangoJSONEncoder` class.

        Defaults to ``json.JSONEncoder``.

    .. attribute:: decoder

        A :py:class:`json.JSONDecoder` subclass to deserialize the input. Your
        deserialization may need to account for the fact that you can't be
        certain of the input type. For example, you run the risk of returning a
        ``datetime`` that was actually a string that just happened to be in the
        same format chosen for ``datetime``\s.

        The ``decoder`` can be used to validate the input. If
        :py:class:`json.JSONDecodeError` is raised during the deserialization,
        a ``ValidationError`` will be raised.

        Defaults to ``json.JSONDecoder``.

    .. note::

        If you use a :class:`ModelForm <django.forms.ModelForm>`, the
        ``encoder`` and ``decoder`` from :class:`~django.db.models.JSONField`
        will be used.

    .. admonition:: User friendly forms

        ``JSONField`` is not particularly user friendly in most cases. However,
        it is a useful way to format data from a client-side widget for
        submission to the server.

``MultipleChoiceField``
-----------------------

.. class:: MultipleChoiceField(**kwargs)

    * Default widget: :class:`SelectMultiple`
    * Empty value: ``[]`` (an empty list)
    * Normalizes to: A list of strings.
    * Validates that every value in the given list of values exists in the list
      of choices.
    * Error message keys: ``required``, ``invalid_choice``, ``invalid_list``

    The ``invalid_choice`` error message may contain ``%(value)s``, which will be
    replaced with the selected choice.

    Takes one extra required argument, ``choices``, as for :class:`ChoiceField`.

``NullBooleanField``
--------------------

.. class:: NullBooleanField(**kwargs)

    * Default widget: :class:`NullBooleanSelect`
    * Empty value: ``None``
    * Normalizes to: A Python ``True``, ``False`` or ``None`` value.
    * Validates nothing (i.e., it never raises a ``ValidationError``).

    ``NullBooleanField`` may be used with widgets such as
    :class:`~django.forms.Select` or :class:`~django.forms.RadioSelect`
    by providing the widget ``choices``::

        NullBooleanField(
            widget=Select(
                choices=[
                    ("", "Unknown"),
                    (True, "Yes"),
                    (False, "No"),
                ]
            )
        )

``RegexField``
--------------

.. class:: RegexField(**kwargs)

    * Default widget: :class:`TextInput`
    * Empty value: Whatever you've given as ``empty_value``.
    * Normalizes to: A string.
    * Uses :class:`~django.core.validators.RegexValidator` to validate that
      the given value matches a certain regular expression.
    * Error message keys: ``required``, ``invalid``

    Takes one required argument:

    .. attribute:: regex

        A regular expression specified either as a string or a compiled regular
        expression object.

    Also takes ``max_length``, ``min_length``, ``strip``, and ``empty_value``
    which work just as they do for :class:`CharField`.

    .. attribute:: strip

        Defaults to ``False``. If enabled, stripping will be applied before the
        regex validation.

``SlugField``
-------------

.. class:: SlugField(**kwargs)

   * Default widget: :class:`TextInput`
   * Empty value: Whatever you've given as :attr:`empty_value`.
   * Normalizes to: A string.
   * Uses :class:`~django.core.validators.validate_slug` or
     :class:`~django.core.validators.validate_unicode_slug` to validate that
     the given value contains only letters, numbers, underscores, and hyphens.
   * Error messages: ``required``, ``invalid``

   This field is intended for use in representing a model
   :class:`~django.db.models.SlugField` in forms.

   Takes two optional parameters:

   .. attribute:: allow_unicode

       A boolean instructing the field to accept Unicode letters in addition
       to ASCII letters. Defaults to ``False``.

   .. attribute:: empty_value

       The value to use to represent "empty". Defaults to an empty string.

``TimeField``
-------------

.. class:: TimeField(**kwargs)

    * Default widget: :class:`TimeInput`
    * Empty value: ``None``
    * Normalizes to: A Python ``datetime.time`` object.
    * Validates that the given value is either a ``datetime.time`` or string
      formatted in a particular time format.
    * Error message keys: ``required``, ``invalid``

    Takes one optional argument:

    .. attribute:: input_formats

        An iterable of formats used to attempt to convert a string to a valid
        ``datetime.time`` object.

    If no ``input_formats`` argument is provided, the default input formats are
    taken from the active locale format ``TIME_INPUT_FORMATS`` key, or from
    :setting:`TIME_INPUT_FORMATS` if localization is disabled. See also
    :doc:`format localization </topics/i18n/formatting>`.

``TypedChoiceField``
--------------------

.. class:: TypedChoiceField(**kwargs)

    Just like a :class:`ChoiceField`, except :class:`TypedChoiceField` takes two
    extra arguments, :attr:`coerce` and :attr:`empty_value`.

    * Default widget: :class:`Select`
    * Empty value: Whatever you've given as :attr:`empty_value`.
    * Normalizes to: A value of the type provided by the :attr:`coerce`
      argument.
    * Validates that the given value exists in the list of choices and can be
      coerced.
    * Error message keys: ``required``, ``invalid_choice``

    Takes extra arguments:

    .. attribute:: coerce

        A function that takes one argument and returns a coerced value. Examples
        include the built-in ``int``, ``float``, ``bool`` and other types. Defaults
        to an identity function. Note that coercion happens after input
        validation, so it is possible to coerce to a value not present in
        ``choices``.

    .. attribute:: empty_value

        The value to use to represent "empty." Defaults to the empty string;
        ``None`` is another common choice here. Note that this value will not be
        coerced by the function given in the ``coerce`` argument, so choose it
        accordingly.

``TypedMultipleChoiceField``
----------------------------

.. class:: TypedMultipleChoiceField(**kwargs)

    Just like a :class:`MultipleChoiceField`, except :class:`TypedMultipleChoiceField`
    takes two extra arguments, ``coerce`` and ``empty_value``.

    * Default widget: :class:`SelectMultiple`
    * Empty value: Whatever you've given as ``empty_value``
    * Normalizes to: A list of values of the type provided by the ``coerce``
      argument.
    * Validates that the given values exists in the list of choices and can be
      coerced.
    * Error message keys: ``required``, ``invalid_choice``

    The ``invalid_choice`` error message may contain ``%(value)s``, which will be
    replaced with the selected choice.

    Takes two extra arguments, ``coerce`` and ``empty_value``, as for
    :class:`TypedChoiceField`.

``URLField``
------------

.. class:: URLField(**kwargs)

    * Default widget: :class:`URLInput`
    * Empty value: Whatever you've given as ``empty_value``.
    * Normalizes to: A string.
    * Uses :class:`~django.core.validators.URLValidator` to validate that the
      given value is a valid URL.
    * Error message keys: ``required``, ``invalid``

    Has the optional arguments ``max_length``, ``min_length``, ``empty_value``
    which work just as they do for :class:`CharField`, and ``assume_scheme``
    that defaults to ``"http"``.

    .. versionchanged:: 5.0

        The ``assume_scheme`` argument was added.

    .. deprecated:: 5.0

        The default value for ``assume_scheme`` will change from ``"http"`` to
        ``"https"`` in Django 6.0.

``UUIDField``
-------------

.. class:: UUIDField(**kwargs)

    * Default widget: :class:`TextInput`
    * Empty value: ``None``
    * Normalizes to: A :class:`~python:uuid.UUID` object.
    * Error message keys: ``required``, ``invalid``

    This field will accept any string format accepted as the ``hex`` argument
    to the :class:`~python:uuid.UUID` constructor.

Slightly complex built-in ``Field`` classes
===========================================

``ComboField``
--------------

.. class:: ComboField(**kwargs)

    * Default widget: :class:`TextInput`
    * Empty value: ``''`` (an empty string)
    * Normalizes to: A string.
    * Validates the given value against each of the fields specified
      as an argument to the ``ComboField``.
    * Error message keys: ``required``, ``invalid``

    Takes one extra required argument:

    .. attribute:: fields

        The list of fields that should be used to validate the field's value (in
        the order in which they are provided).

            >>> from django.forms import ComboField
            >>> f = ComboField(fields=[CharField(max_length=20), EmailField()])
            >>> f.clean('test@example.com')
            'test@example.com'
            >>> f.clean('longemailaddress@example.com')
            Traceback (most recent call last):
            ...
            ValidationError: ['Ensure this value has at most 20 characters (it has 28).']

``MultiValueField``
-------------------

.. class:: MultiValueField(fields=(), **kwargs)

    * Default widget: :class:`TextInput`
    * Empty value: ``''`` (an empty string)
    * Normalizes to: the type returned by the ``compress`` method of the subclass.
    * Validates the given value against each of the fields specified
      as an argument to the ``MultiValueField``.
    * Error message keys: ``required``, ``invalid``, ``incomplete``

    Aggregates the logic of multiple fields that together produce a single
    value.

    This field is abstract and must be subclassed. In contrast with the
    single-value fields, subclasses of :class:`MultiValueField` must not
    implement :meth:`~django.forms.Field.clean` but instead - implement
    :meth:`~MultiValueField.compress`.

    Takes one extra required argument:

    .. attribute:: fields

        A tuple of fields whose values are cleaned and subsequently combined
        into a single value.  Each value of the field is cleaned by the
        corresponding field in ``fields`` -- the first value is cleaned by the
        first field, the second value is cleaned by the second field, etc.
        Once all fields are cleaned, the list of clean values is combined into
        a single value by :meth:`~MultiValueField.compress`.

    Also takes some optional arguments:

    .. attribute:: require_all_fields

        Defaults to ``True``, in which case a ``required`` validation error
        will be raised if no value is supplied for any field.

        When set to ``False``, the :attr:`Field.required` attribute can be set
        to ``False`` for individual fields to make them optional. If no value
        is supplied for a required field, an ``incomplete`` validation error
        will be raised.

        A default ``incomplete`` error message can be defined on the
        :class:`MultiValueField` subclass, or different messages can be defined
        on each individual field. For example::

            from django.core.validators import RegexValidator


            class PhoneField(MultiValueField):
                def __init__(self, **kwargs):
                    # Define one message for all fields.
                    error_messages = {
                        "incomplete": "Enter a country calling code and a phone number.",
                    }
                    # Or define a different message for each field.
                    fields = (
                        CharField(
                            error_messages={"incomplete": "Enter a country calling code."},
                            validators=[
                                RegexValidator(r"^[0-9]+$", "Enter a valid country calling code."),
                            ],
                        ),
                        CharField(
                            error_messages={"incomplete": "Enter a phone number."},
                            validators=[RegexValidator(r"^[0-9]+$", "Enter a valid phone number.")],
                        ),
                        CharField(
                            validators=[RegexValidator(r"^[0-9]+$", "Enter a valid extension.")],
                            required=False,
                        ),
                    )
                    super().__init__(
                        error_messages=error_messages,
                        fields=fields,
                        require_all_fields=False,
                        **kwargs
                    )

    .. attribute:: MultiValueField.widget

        Must be a subclass of :class:`django.forms.MultiWidget`.
        Default value is :class:`~django.forms.TextInput`, which
        probably is not very useful in this case.

    .. method:: compress(data_list)

        Takes a list of valid values and returns  a "compressed" version of
        those values -- in a single value. For example,
        :class:`SplitDateTimeField` is a subclass which combines a time field
        and a date field into a ``datetime`` object.

        This method must be implemented in the subclasses.

``SplitDateTimeField``
----------------------

.. class:: SplitDateTimeField(**kwargs)

    * Default widget: :class:`SplitDateTimeWidget`
    * Empty value: ``None``
    * Normalizes to: A Python ``datetime.datetime`` object.
    * Validates that the given value is a ``datetime.datetime`` or string
      formatted in a particular datetime format.
    * Error message keys: ``required``, ``invalid``, ``invalid_date``,
      ``invalid_time``

    Takes two optional arguments:

    .. attribute:: input_date_formats

        A list of formats used to attempt to convert a string to a valid
        ``datetime.date`` object.

    If no ``input_date_formats`` argument is provided, the default input formats
    for :class:`DateField` are used.

    .. attribute:: input_time_formats

        A list of formats used to attempt to convert a string to a valid
        ``datetime.time`` object.

    If no ``input_time_formats`` argument is provided, the default input formats
    for :class:`TimeField` are used.

.. _fields-which-handle-relationships:

Fields which handle relationships
=================================

Two fields are available for representing relationships between
models: :class:`ModelChoiceField` and
:class:`ModelMultipleChoiceField`.  Both of these fields require a
single ``queryset`` parameter that is used to create the choices for
the field.  Upon form validation, these fields will place either one
model object (in the case of ``ModelChoiceField``) or multiple model
objects (in the case of ``ModelMultipleChoiceField``) into the
``cleaned_data`` dictionary of the form.

For more complex uses, you can specify ``queryset=None`` when declaring the
form field and then populate the ``queryset`` in the form's ``__init__()``
method::

    class FooMultipleChoiceForm(forms.Form):
        foo_select = forms.ModelMultipleChoiceField(queryset=None)

        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.fields["foo_select"].queryset = ...

Both ``ModelChoiceField`` and ``ModelMultipleChoiceField`` have an ``iterator``
attribute which specifies the class used to iterate over the queryset when
generating choices. See :ref:`iterating-relationship-choices` for details.

``ModelChoiceField``
--------------------

.. class:: ModelChoiceField(**kwargs)

    * Default widget: :class:`Select`
    * Empty value: ``None``
    * Normalizes to: A model instance.
    * Validates that the given id exists in the queryset.
    * Error message keys: ``required``, ``invalid_choice``

    The ``invalid_choice`` error message may contain ``%(value)s``, which will
    be replaced with the selected choice.

    Allows the selection of a single model object, suitable for representing a
    foreign key. Note that the default widget for ``ModelChoiceField`` becomes
    impractical when the number of entries increases. You should avoid using it
    for more than 100 items.

    A single argument is required:

    .. attribute:: queryset

        A ``QuerySet`` of model objects from which the choices for the field
        are derived and which is used to validate the user's selection. It's
        evaluated when the form is rendered.

    ``ModelChoiceField`` also takes several optional arguments:

    .. attribute:: empty_label

        By default the ``<select>`` widget used by ``ModelChoiceField`` will have an
        empty choice at the top of the list. You can change the text of this
        label (which is ``"---------"`` by default) with the ``empty_label``
        attribute, or you can disable the empty label entirely by setting
        ``empty_label`` to ``None``::

            # A custom empty label
            field1 = forms.ModelChoiceField(queryset=..., empty_label="(Nothing)")

            # No empty label
            field2 = forms.ModelChoiceField(queryset=..., empty_label=None)

        Note that no empty choice is created (regardless of the value of
        ``empty_label``) if a ``ModelChoiceField`` is required and has a
        default initial value, or a ``widget`` is set to
        :class:`~django.forms.RadioSelect` and the
        :attr:`~ModelChoiceField.blank` argument is ``False``.

    .. attribute:: to_field_name

        This optional argument is used to specify the field to use as the value
        of the choices in the field's widget. Be sure it's a unique field for
        the model, otherwise the selected value could match more than one
        object. By default it is set to ``None``, in which case the primary key
        of each object will be used. For example::

            # No custom to_field_name
            field1 = forms.ModelChoiceField(queryset=...)

        would yield:

        .. code-block:: html

            <select id="id_field1" name="field1">
            <option value="obj1.pk">Object1</option>
            <option value="obj2.pk">Object2</option>
            ...
            </select>

        and::

            # to_field_name provided
            field2 = forms.ModelChoiceField(queryset=..., to_field_name="name")

        would yield:

        .. code-block:: html

            <select id="id_field2" name="field2">
            <option value="obj1.name">Object1</option>
            <option value="obj2.name">Object2</option>
            ...
            </select>

    .. attribute:: blank

        When using the :class:`~django.forms.RadioSelect` widget, this optional
        boolean argument determines whether an empty choice is created. By
        default, ``blank`` is ``False``, in which case no empty choice is
        created.

    ``ModelChoiceField`` also has the attribute:

    .. attribute:: iterator

        The iterator class used to generate field choices from ``queryset``. By
        default, :class:`ModelChoiceIterator`.

    The ``__str__()`` method of the model will be called to generate string
    representations of the objects for use in the field's choices. To provide
    customized representations, subclass ``ModelChoiceField`` and override
    ``label_from_instance``. This method will receive a model object and should
    return a string suitable for representing it. For example::

        from django.forms import ModelChoiceField


        class MyModelChoiceField(ModelChoiceField):
            def label_from_instance(self, obj):
                return "My Object #%i" % obj.id

``ModelMultipleChoiceField``
----------------------------

.. class:: ModelMultipleChoiceField(**kwargs)

    * Default widget: :class:`SelectMultiple`
    * Empty value: An empty ``QuerySet`` (``self.queryset.none()``)
    * Normalizes to: A ``QuerySet`` of model instances.
    * Validates that every id in the given list of values exists in the
      queryset.
    * Error message keys: ``required``, ``invalid_list``, ``invalid_choice``,
      ``invalid_pk_value``

    The ``invalid_choice`` message may contain ``%(value)s`` and the
    ``invalid_pk_value`` message may contain ``%(pk)s``, which will be
    substituted by the appropriate values.

    Allows the selection of one or more model objects, suitable for
    representing a many-to-many relation. As with :class:`ModelChoiceField`,
    you can use ``label_from_instance`` to customize the object
    representations.

    A single argument is required:

    .. attribute:: queryset

        Same as :class:`ModelChoiceField.queryset`.

    Takes one optional argument:

    .. attribute:: to_field_name

        Same as :class:`ModelChoiceField.to_field_name`.

    ``ModelMultipleChoiceField`` also has the attribute:

    .. attribute:: iterator

        Same as :class:`ModelChoiceField.iterator`.

.. _iterating-relationship-choices:

Iterating relationship choices
------------------------------

By default, :class:`ModelChoiceField` and :class:`ModelMultipleChoiceField` use
:class:`ModelChoiceIterator` to generate their field ``choices``.

When iterated, ``ModelChoiceIterator`` yields 2-tuple choices containing
:class:`ModelChoiceIteratorValue` instances as the first ``value`` element in
each choice. ``ModelChoiceIteratorValue`` wraps the choice value while
maintaining a reference to the source model instance that can be used in custom
widget implementations, for example, to add `data-* attributes`_ to
``<option>`` elements.

.. _`data-* attributes`: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/data-*

For example, consider the following models::

    from django.db import models


    class Topping(models.Model):
        name = models.CharField(max_length=100)
        price = models.DecimalField(decimal_places=2, max_digits=6)

        def __str__(self):
            return self.name


    class Pizza(models.Model):
        topping = models.ForeignKey(Topping, on_delete=models.CASCADE)

You can use a :class:`~django.forms.Select` widget subclass to include
the value of ``Topping.price`` as the HTML attribute ``data-price`` for each
``<option>`` element::

    from django import forms


    class ToppingSelect(forms.Select):
        def create_option(
            self, name, value, label, selected, index, subindex=None, attrs=None
        ):
            option = super().create_option(
                name, value, label, selected, index, subindex, attrs
            )
            if value:
                option["attrs"]["data-price"] = value.instance.price
            return option


    class PizzaForm(forms.ModelForm):
        class Meta:
            model = Pizza
            fields = ["topping"]
            widgets = {"topping": ToppingSelect}

This will render the ``Pizza.topping`` select as:

.. code-block:: html

    <select id="id_topping" name="topping" required>
    <option value="" selected>---------</option>
    <option value="1" data-price="1.50">mushrooms</option>
    <option value="2" data-price="1.25">onions</option>
    <option value="3" data-price="1.75">peppers</option>
    <option value="4" data-price="2.00">pineapple</option>
    </select>

For more advanced usage you may subclass ``ModelChoiceIterator`` in order to
customize the yielded 2-tuple choices.

``ModelChoiceIterator``
~~~~~~~~~~~~~~~~~~~~~~~

.. class:: ModelChoiceIterator(field)

    The default class assigned to the ``iterator`` attribute of
    :class:`ModelChoiceField` and :class:`ModelMultipleChoiceField`. An
    iterable that yields 2-tuple choices from the queryset.

    A single argument is required:

    .. attribute:: field

        The instance of ``ModelChoiceField`` or ``ModelMultipleChoiceField`` to
        iterate and yield choices.

    ``ModelChoiceIterator`` has the following method:

    .. method:: __iter__()

        Yields 2-tuple choices, in the ``(value, label)`` format used by
        :attr:`ChoiceField.choices`. The first ``value`` element is a
        :class:`ModelChoiceIteratorValue` instance.

``ModelChoiceIteratorValue``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. class:: ModelChoiceIteratorValue(value, instance)

    Two arguments are required:

    .. attribute:: value

        The value of the choice. This value is used to render the ``value``
        attribute of an HTML ``<option>`` element.

    .. attribute:: instance

        The model instance from the queryset. The instance can be accessed in
        custom ``ChoiceWidget.create_option()`` implementations to adjust the
        rendered HTML.

    ``ModelChoiceIteratorValue`` has the following method:

    .. method:: __str__()

        Return ``value`` as a string to be rendered in HTML.

Creating custom fields
======================

If the built-in ``Field`` classes don't meet your needs, you can create custom
``Field`` classes. To do this, create a subclass of ``django.forms.Field``. Its
only requirements are that it implement a ``clean()`` method and that its
``__init__()`` method accept the core arguments mentioned above (``required``,
``label``, ``initial``, ``widget``, ``help_text``).

You can also customize how a field will be accessed by overriding
:meth:`~django.forms.Field.get_bound_field()`.