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
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
|
=============
The Forms API
=============
.. module:: django.forms
.. admonition:: About this document
This document covers the gritty details of Django's forms API. You should
read the :doc:`introduction to working with forms </topics/forms/index>`
first.
.. _ref-forms-api-bound-unbound:
Bound and unbound forms
=======================
A :class:`Form` instance is either **bound** to a set of data, or **unbound**.
* If it's **bound** to a set of data, it's capable of validating that data
and rendering the form as HTML with the data displayed in the HTML.
* If it's **unbound**, it cannot do validation (because there's no data to
validate!), but it can still render the blank form as HTML.
.. class:: Form
To create an unbound :class:`Form` instance, instantiate the class:
.. code-block:: pycon
>>> f = ContactForm()
To bind data to a form, pass the data as a dictionary as the first parameter to
your :class:`Form` class constructor:
.. code-block:: pycon
>>> data = {
... "subject": "hello",
... "message": "Hi there",
... "sender": "foo@example.com",
... "cc_myself": True,
... }
>>> f = ContactForm(data)
In this dictionary, the keys are the field names, which correspond to the
attributes in your :class:`Form` class. The values are the data you're trying to
validate. These will usually be strings, but there's no requirement that they be
strings; the type of data you pass depends on the :class:`Field`, as we'll see
in a moment.
.. attribute:: Form.is_bound
If you need to distinguish between bound and unbound form instances at runtime,
check the value of the form's :attr:`~Form.is_bound` attribute:
.. code-block:: pycon
>>> f = ContactForm()
>>> f.is_bound
False
>>> f = ContactForm({"subject": "hello"})
>>> f.is_bound
True
Note that passing an empty dictionary creates a *bound* form with empty data:
.. code-block:: pycon
>>> f = ContactForm({})
>>> f.is_bound
True
If you have a bound :class:`Form` instance and want to change the data somehow,
or if you want to bind an unbound :class:`Form` instance to some data, create
another :class:`Form` instance. There is no way to change data in a
:class:`Form` instance. Once a :class:`Form` instance has been created, you
should consider its data immutable, whether it has data or not.
Using forms to validate data
============================
.. method:: Form.clean()
Implement a ``clean()`` method on your ``Form`` when you must add custom
validation for fields that are interdependent. See
:ref:`validating-fields-with-clean` for example usage.
.. method:: Form.is_valid()
The primary task of a :class:`Form` object is to validate data. With a bound
:class:`Form` instance, call the :meth:`~Form.is_valid` method to run validation
and return a boolean designating whether the data was valid:
.. code-block:: pycon
>>> data = {
... "subject": "hello",
... "message": "Hi there",
... "sender": "foo@example.com",
... "cc_myself": True,
... }
>>> f = ContactForm(data)
>>> f.is_valid()
True
Let's try with some invalid data. In this case, ``subject`` is blank (an error,
because all fields are required by default) and ``sender`` is not a valid
email address:
.. code-block:: pycon
>>> data = {
... "subject": "",
... "message": "Hi there",
... "sender": "invalid email address",
... "cc_myself": True,
... }
>>> f = ContactForm(data)
>>> f.is_valid()
False
.. attribute:: Form.errors
Access the :attr:`~Form.errors` attribute to get a dictionary of error
messages:
.. code-block:: pycon
>>> f.errors
{'sender': ['Enter a valid email address.'], 'subject': ['This field is required.']}
In this dictionary, the keys are the field names, and the values are lists of
strings representing the error messages. The error messages are stored
in lists because a field can have multiple error messages.
You can access :attr:`~Form.errors` without having to call
:meth:`~Form.is_valid` first. The form's data will be validated the first time
either you call :meth:`~Form.is_valid` or access :attr:`~Form.errors`.
The validation routines will only get called once, regardless of how many times
you access :attr:`~Form.errors` or call :meth:`~Form.is_valid`. This means that
if validation has side effects, those side effects will only be triggered once.
.. method:: Form.errors.as_data()
Returns a ``dict`` that maps fields to their original ``ValidationError``
instances.
>>> f.errors.as_data()
{'sender': [ValidationError(['Enter a valid email address.'])],
'subject': [ValidationError(['This field is required.'])]}
Use this method anytime you need to identify an error by its ``code``. This
enables things like rewriting the error's message or writing custom logic in a
view when a given error is present. It can also be used to serialize the errors
in a custom format (e.g. XML); for instance, :meth:`~Form.errors.as_json()`
relies on ``as_data()``.
The need for the ``as_data()`` method is due to backwards compatibility.
Previously ``ValidationError`` instances were lost as soon as their
**rendered** error messages were added to the ``Form.errors`` dictionary.
Ideally ``Form.errors`` would have stored ``ValidationError`` instances
and methods with an ``as_`` prefix could render them, but it had to be done
the other way around in order not to break code that expects rendered error
messages in ``Form.errors``.
.. method:: Form.errors.as_json(escape_html=False)
Returns the errors serialized as JSON.
>>> f.errors.as_json()
{"sender": [{"message": "Enter a valid email address.", "code": "invalid"}],
"subject": [{"message": "This field is required.", "code": "required"}]}
By default, ``as_json()`` does not escape its output. If you are using it for
something like AJAX requests to a form view where the client interprets the
response and inserts errors into the page, you'll want to be sure to escape the
results on the client-side to avoid the possibility of a cross-site scripting
attack. You can do this in JavaScript with ``element.textContent = errorText``
or with jQuery's ``$(el).text(errorText)`` (rather than its ``.html()``
function).
If for some reason you don't want to use client-side escaping, you can also
set ``escape_html=True`` and error messages will be escaped so you can use them
directly in HTML.
.. method:: Form.errors.get_json_data(escape_html=False)
Returns the errors as a dictionary suitable for serializing to JSON.
:meth:`Form.errors.as_json()` returns serialized JSON, while this returns the
error data before it's serialized.
The ``escape_html`` parameter behaves as described in
:meth:`Form.errors.as_json()`.
.. method:: Form.add_error(field, error)
This method allows adding errors to specific fields from within the
``Form.clean()`` method, or from outside the form altogether; for instance
from a view.
The ``field`` argument is the name of the field to which the errors
should be added. If its value is ``None`` the error will be treated as
a non-field error as returned by :meth:`Form.non_field_errors()
<django.forms.Form.non_field_errors>`.
The ``error`` argument can be a string, or preferably an instance of
``ValidationError``. See :ref:`raising-validation-error` for best practices
when defining form errors.
Note that ``Form.add_error()`` automatically removes the relevant field from
``cleaned_data``.
.. method:: Form.has_error(field, code=None)
This method returns a boolean designating whether a field has an error with
a specific error ``code``. If ``code`` is ``None``, it will return ``True``
if the field contains any errors at all.
To check for non-field errors use
:data:`~django.core.exceptions.NON_FIELD_ERRORS` as the ``field`` parameter.
.. method:: Form.non_field_errors()
This method returns the list of errors from :attr:`Form.errors
<django.forms.Form.errors>` that aren't associated with a particular field.
This includes ``ValidationError``\s that are raised in :meth:`Form.clean()
<django.forms.Form.clean>` and errors added using :meth:`Form.add_error(None,
"...") <django.forms.Form.add_error>`.
Behavior of unbound forms
-------------------------
It's meaningless to validate a form with no data, but, for the record, here's
what happens with unbound forms:
.. code-block:: pycon
>>> f = ContactForm()
>>> f.is_valid()
False
>>> f.errors
{}
.. _ref-forms-initial-form-values:
Initial form values
===================
.. attribute:: Form.initial
Use :attr:`~Form.initial` to declare the initial value of form fields at
runtime. For example, you might want to fill in a ``username`` field with the
username of the current session.
To accomplish this, use the :attr:`~Form.initial` argument to a :class:`Form`.
This argument, if given, should be a dictionary mapping field names to initial
values. Only include the fields for which you're specifying an initial value;
it's not necessary to include every field in your form. For example:
.. code-block:: pycon
>>> f = ContactForm(initial={"subject": "Hi there!"})
These values are only displayed for unbound forms, and they're not used as
fallback values if a particular value isn't provided.
If a :class:`~django.forms.Field` defines :attr:`~Field.initial` *and* you
include :attr:`~Form.initial` when instantiating the ``Form``, then the latter
``initial`` will have precedence. In this example, ``initial`` is provided both
at the field level and at the form instance level, and the latter gets
precedence:
.. code-block:: pycon
>>> from django import forms
>>> class CommentForm(forms.Form):
... name = forms.CharField(initial="class")
... url = forms.URLField()
... comment = forms.CharField()
...
>>> f = CommentForm(initial={"name": "instance"}, auto_id=False)
>>> print(f)
<div>Name:<input type="text" name="name" value="instance" required></div>
<div>Url:<input type="url" name="url" required></div>
<div>Comment:<input type="text" name="comment" required></div>
.. method:: Form.get_initial_for_field(field, field_name)
Returns the initial data for a form field. It retrieves the data from
:attr:`Form.initial` if present, otherwise trying :attr:`Field.initial`.
Callable values are evaluated.
It is recommended to use :attr:`BoundField.initial` over
:meth:`~Form.get_initial_for_field()` because ``BoundField.initial`` has a
simpler interface. Also, unlike :meth:`~Form.get_initial_for_field()`,
:attr:`BoundField.initial` caches its values. This is useful especially when
dealing with callables whose return values can change (e.g. ``datetime.now`` or
``uuid.uuid4``):
.. code-block:: pycon
>>> import uuid
>>> class UUIDCommentForm(CommentForm):
... identifier = forms.UUIDField(initial=uuid.uuid4)
...
>>> f = UUIDCommentForm()
>>> f.get_initial_for_field(f.fields["identifier"], "identifier")
UUID('972ca9e4-7bfe-4f5b-af7d-07b3aa306334')
>>> f.get_initial_for_field(f.fields["identifier"], "identifier")
UUID('1b411fab-844e-4dec-bd4f-e9b0495f04d0')
>>> # Using BoundField.initial, for comparison
>>> f["identifier"].initial
UUID('28a09c59-5f00-4ed9-9179-a3b074fa9c30')
>>> f["identifier"].initial
UUID('28a09c59-5f00-4ed9-9179-a3b074fa9c30')
Checking which form data has changed
====================================
.. method:: Form.has_changed()
Use the ``has_changed()`` method on your ``Form`` when you need to check if the
form data has been changed from the initial data.
>>> data = {'subject': 'hello',
... 'message': 'Hi there',
... 'sender': 'foo@example.com',
... 'cc_myself': True}
>>> f = ContactForm(data, initial=data)
>>> f.has_changed()
False
When the form is submitted, we reconstruct it and provide the original data
so that the comparison can be done:
>>> f = ContactForm(request.POST, initial=data)
>>> f.has_changed()
``has_changed()`` will be ``True`` if the data from ``request.POST`` differs
from what was provided in :attr:`~Form.initial` or ``False`` otherwise. The
result is computed by calling :meth:`Field.has_changed` for each field in the
form.
.. attribute:: Form.changed_data
The ``changed_data`` attribute returns a list of the names of the fields whose
values in the form's bound data (usually ``request.POST``) differ from what was
provided in :attr:`~Form.initial`. It returns an empty list if no data differs.
>>> f = ContactForm(request.POST, initial=data)
>>> if f.has_changed():
... print("The following fields changed: %s" % ", ".join(f.changed_data))
>>> f.changed_data
['subject', 'message']
Accessing the fields from the form
==================================
.. attribute:: Form.fields
You can access the fields of :class:`Form` instance from its ``fields``
attribute:
.. code-block:: pycon
>>> for row in f.fields.values():
... print(row)
...
<django.forms.fields.CharField object at 0x7ffaac632510>
<django.forms.fields.URLField object at 0x7ffaac632f90>
<django.forms.fields.CharField object at 0x7ffaac3aa050>
>>> f.fields["name"]
<django.forms.fields.CharField object at 0x7ffaac6324d0>
You can alter the field and :class:`.BoundField` of :class:`Form` instance to
change the way it is presented in the form:
.. code-block:: pycon
>>> f.as_div().split("</div>")[0]
'<div><label for="id_subject">Subject:</label><input type="text" name="subject" maxlength="100" required id="id_subject">'
>>> f["subject"].label = "Topic"
>>> f.as_div().split("</div>")[0]
'<div><label for="id_subject">Topic:</label><input type="text" name="subject" maxlength="100" required id="id_subject">'
Beware not to alter the ``base_fields`` attribute because this modification
will influence all subsequent ``ContactForm`` instances within the same Python
process:
.. code-block:: pycon
>>> f.base_fields["subject"].label_suffix = "?"
>>> another_f = CommentForm(auto_id=False)
>>> f.as_div().split("</div>")[0]
'<div><label for="id_subject">Subject?</label><input type="text" name="subject" maxlength="100" required id="id_subject">'
Accessing "clean" data
======================
.. attribute:: Form.cleaned_data
Each field in a :class:`Form` class is responsible not only for validating
data, but also for "cleaning" it -- normalizing it to a consistent format. This
is a nice feature, because it allows data for a particular field to be input in
a variety of ways, always resulting in consistent output.
For example, :class:`~django.forms.DateField` normalizes input into a
Python ``datetime.date`` object. Regardless of whether you pass it a string in
the format ``'1994-07-15'``, a ``datetime.date`` object, or a number of other
formats, ``DateField`` will always normalize it to a ``datetime.date`` object
as long as it's valid.
Once you've created a :class:`~Form` instance with a set of data and validated
it, you can access the clean data via its ``cleaned_data`` attribute:
.. code-block:: pycon
>>> data = {
... "subject": "hello",
... "message": "Hi there",
... "sender": "foo@example.com",
... "cc_myself": True,
... }
>>> f = ContactForm(data)
>>> f.is_valid()
True
>>> f.cleaned_data
{'cc_myself': True, 'message': 'Hi there', 'sender': 'foo@example.com', 'subject': 'hello'}
Note that any text-based field -- such as ``CharField`` or ``EmailField`` --
always cleans the input into a string. We'll cover the encoding implications
later in this document.
If your data does *not* validate, the ``cleaned_data`` dictionary contains
only the valid fields:
.. code-block:: pycon
>>> data = {
... "subject": "",
... "message": "Hi there",
... "sender": "invalid email address",
... "cc_myself": True,
... }
>>> f = ContactForm(data)
>>> f.is_valid()
False
>>> f.cleaned_data
{'cc_myself': True, 'message': 'Hi there'}
``cleaned_data`` will always *only* contain a key for fields defined in the
``Form``, even if you pass extra data when you define the ``Form``. In this
example, we pass a bunch of extra fields to the ``ContactForm`` constructor,
but ``cleaned_data`` contains only the form's fields:
.. code-block:: pycon
>>> data = {
... "subject": "hello",
... "message": "Hi there",
... "sender": "foo@example.com",
... "cc_myself": True,
... "extra_field_1": "foo",
... "extra_field_2": "bar",
... "extra_field_3": "baz",
... }
>>> f = ContactForm(data)
>>> f.is_valid()
True
>>> f.cleaned_data # Doesn't contain extra_field_1, etc.
{'cc_myself': True, 'message': 'Hi there', 'sender': 'foo@example.com', 'subject': 'hello'}
When the ``Form`` is valid, ``cleaned_data`` will include a key and value for
*all* its fields, even if the data didn't include a value for some optional
fields. In this example, the data dictionary doesn't include a value for the
``nick_name`` field, but ``cleaned_data`` includes it, with an empty value:
.. code-block:: pycon
>>> from django import forms
>>> class OptionalPersonForm(forms.Form):
... first_name = forms.CharField()
... last_name = forms.CharField()
... nick_name = forms.CharField(required=False)
...
>>> data = {"first_name": "John", "last_name": "Lennon"}
>>> f = OptionalPersonForm(data)
>>> f.is_valid()
True
>>> f.cleaned_data
{'nick_name': '', 'first_name': 'John', 'last_name': 'Lennon'}
In this above example, the ``cleaned_data`` value for ``nick_name`` is set to an
empty string, because ``nick_name`` is ``CharField``, and ``CharField``\s treat
empty values as an empty string. Each field type knows what its "blank" value
is -- e.g., for ``DateField``, it's ``None`` instead of the empty string. For
full details on each field's behavior in this case, see the "Empty value" note
for each field in the "Built-in ``Field`` classes" section below.
You can write code to perform validation for particular form fields (based on
their name) or for the form as a whole (considering combinations of various
fields). More information about this is in :doc:`/ref/forms/validation`.
.. _ref-forms-api-outputting-html:
Outputting forms as HTML
========================
The second task of a ``Form`` object is to render itself as HTML. To do so,
``print`` it:
.. code-block:: pycon
>>> f = ContactForm()
>>> print(f)
<div><label for="id_subject">Subject:</label><input type="text" name="subject" maxlength="100" required id="id_subject"></div>
<div><label for="id_message">Message:</label><input type="text" name="message" required id="id_message"></div>
<div><label for="id_sender">Sender:</label><input type="email" name="sender" required id="id_sender"></div>
<div><label for="id_cc_myself">Cc myself:</label><input type="checkbox" name="cc_myself" id="id_cc_myself"></div>
If the form is bound to data, the HTML output will include that data
appropriately. For example, if a field is represented by an
``<input type="text">``, the data will be in the ``value`` attribute. If a
field is represented by an ``<input type="checkbox">``, then that HTML will
include ``checked`` if appropriate:
.. code-block:: pycon
>>> data = {
... "subject": "hello",
... "message": "Hi there",
... "sender": "foo@example.com",
... "cc_myself": True,
... }
>>> f = ContactForm(data)
>>> print(f)
<div><label for="id_subject">Subject:</label><input type="text" name="subject" value="hello" maxlength="100" required id="id_subject"></div>
<div><label for="id_message">Message:</label><input type="text" name="message" value="Hi there" required id="id_message"></div>
<div><label for="id_sender">Sender:</label><input type="email" name="sender" value="foo@example.com" required id="id_sender"></div>
<div><label for="id_cc_myself">Cc myself:</label><input type="checkbox" name="cc_myself" id="id_cc_myself" checked></div>
This default output wraps each field with a ``<div>``. Notice the following:
* For flexibility, the output does *not* include the ``<form>`` and ``</form>``
tags or an ``<input type="submit">`` tag. It's your job to do that.
* Each field type has a default HTML representation. ``CharField`` is
represented by an ``<input type="text">`` and ``EmailField`` by an
``<input type="email">``. ``BooleanField(null=False)`` is represented by an
``<input type="checkbox">``. Note these are merely sensible defaults; you can
specify which HTML to use for a given field by using widgets, which we'll
explain shortly.
* The HTML ``name`` for each tag is taken directly from its attribute name
in the ``ContactForm`` class.
* The text label for each field -- e.g. ``'Subject:'``, ``'Message:'`` and
``'Cc myself:'`` is generated from the field name by converting all
underscores to spaces and upper-casing the first letter. Again, note
these are merely sensible defaults; you can also specify labels manually.
* Each text label is surrounded in an HTML ``<label>`` tag, which points
to the appropriate form field via its ``id``. Its ``id``, in turn, is
generated by prepending ``'id_'`` to the field name. The ``id``
attributes and ``<label>`` tags are included in the output by default, to
follow best practices, but you can change that behavior.
* The output uses HTML5 syntax, targeting ``<!DOCTYPE html>``. For example,
it uses boolean attributes such as ``checked`` rather than the XHTML style
of ``checked='checked'``.
Although ``<div>`` output is the default output style when you ``print`` a form
you can customize the output by using your own form template which can be set
site-wide, per-form, or per-instance. See :ref:`reusable-form-templates`.
Default rendering
-----------------
The default rendering when you ``print`` a form uses the following methods and
attributes.
``template_name``
~~~~~~~~~~~~~~~~~
.. attribute:: Form.template_name
The name of the template rendered if the form is cast into a string, e.g. via
``print(form)`` or in a template via ``{{ form }}``.
By default, a property returning the value of the renderer's
:attr:`~django.forms.renderers.BaseRenderer.form_template_name`. You may set it
as a string template name in order to override that for a particular form
class.
``render()``
~~~~~~~~~~~~
.. method:: Form.render(template_name=None, context=None, renderer=None)
The render method is called by ``__str__`` as well as the :meth:`.Form.as_div`,
:meth:`.Form.as_table`, :meth:`.Form.as_p`, and :meth:`.Form.as_ul` methods.
All arguments are optional and default to:
* ``template_name``: :attr:`.Form.template_name`
* ``context``: Value returned by :meth:`.Form.get_context`
* ``renderer``: Value returned by :attr:`.Form.default_renderer`
By passing ``template_name`` you can customize the template used for just a
single call.
``get_context()``
~~~~~~~~~~~~~~~~~
.. method:: Form.get_context()
Return the template context for rendering the form.
The available context is:
* ``form``: The bound form.
* ``fields``: All bound fields, except the hidden fields.
* ``hidden_fields``: All hidden bound fields.
* ``errors``: All non field related or hidden field related form errors.
``template_name_label``
~~~~~~~~~~~~~~~~~~~~~~~
.. attribute:: Form.template_name_label
The template used to render a field's ``<label>``, used when calling
:meth:`BoundField.label_tag`/:meth:`~BoundField.legend_tag`. Can be changed per
form by overriding this attribute or more generally by overriding the default
template, see also :ref:`overriding-built-in-form-templates`.
Output styles
-------------
The recommended approach for changing form output style is to set a custom form
template either site-wide, per-form, or per-instance. See
:ref:`reusable-form-templates` for examples.
The following helper functions are provided for backward compatibility and are
a proxy to :meth:`Form.render` passing a particular ``template_name`` value.
.. note::
Of the framework provided templates and output styles, the default
``as_div()`` is recommended over the ``as_p()``, ``as_table()``, and
``as_ul()`` versions as the template implements ``<fieldset>`` and
``<legend>`` to group related inputs and is easier for screen reader users
to navigate.
Each helper pairs a form method with an attribute giving the appropriate
template name.
``as_div()``
~~~~~~~~~~~~
.. attribute:: Form.template_name_div
The template used by ``as_div()``. Default: ``'django/forms/div.html'``.
.. method:: Form.as_div()
``as_div()`` renders the form as a series of ``<div>`` elements, with each
``<div>`` containing one field, such as:
.. code-block:: pycon
>>> f = ContactForm()
>>> f.as_div()
… gives HTML like:
.. code-block:: html
<div>
<label for="id_subject">Subject:</label>
<input type="text" name="subject" maxlength="100" required id="id_subject">
</div>
<div>
<label for="id_message">Message:</label>
<input type="text" name="message" required id="id_message">
</div>
<div>
<label for="id_sender">Sender:</label>
<input type="email" name="sender" required id="id_sender">
</div>
<div>
<label for="id_cc_myself">Cc myself:</label>
<input type="checkbox" name="cc_myself" id="id_cc_myself">
</div>
``as_p()``
~~~~~~~~~~
.. attribute:: Form.template_name_p
The template used by ``as_p()``. Default: ``'django/forms/p.html'``.
.. method:: Form.as_p()
``as_p()`` renders the form as a series of ``<p>`` tags, with each ``<p>``
containing one field:
.. code-block:: pycon
>>> f = ContactForm()
>>> f.as_p()
'<p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" required></p>\n<p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" required></p>\n<p><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" required></p>\n<p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself"></p>'
>>> print(f.as_p())
<p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" required></p>
<p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" required></p>
<p><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" required></p>
<p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself"></p>
``as_ul()``
~~~~~~~~~~~
.. attribute:: Form.template_name_ul
The template used by ``as_ul()``. Default: ``'django/forms/ul.html'``.
.. method:: Form.as_ul()
``as_ul()`` renders the form as a series of ``<li>`` tags, with each ``<li>``
containing one field. It does *not* include the ``<ul>`` or ``</ul>``, so that
you can specify any HTML attributes on the ``<ul>`` for flexibility:
.. code-block:: pycon
>>> f = ContactForm()
>>> f.as_ul()
'<li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" required></li>\n<li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" required></li>\n<li><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" required></li>\n<li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself"></li>'
>>> print(f.as_ul())
<li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" required></li>
<li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" required></li>
<li><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" required></li>
<li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself"></li>
``as_table()``
~~~~~~~~~~~~~~
.. attribute:: Form.template_name_table
The template used by ``as_table()``. Default: ``'django/forms/table.html'``.
.. method:: Form.as_table()
``as_table()`` renders the form as an HTML ``<table>``:
.. code-block:: pycon
>>> f = ContactForm()
>>> f.as_table()
'<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" required></td></tr>\n<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" required></td></tr>\n<tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" required></td></tr>\n<tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself"></td></tr>'
>>> print(f)
<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" required></td></tr>
<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" required></td></tr>
<tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" required></td></tr>
<tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself"></td></tr>
.. _ref-forms-api-styling-form-rows:
Styling required or erroneous form rows
---------------------------------------
.. attribute:: Form.error_css_class
.. attribute:: Form.required_css_class
It's pretty common to style form rows and fields that are required or have
errors. For example, you might want to present required form rows in bold and
highlight errors in red.
The :class:`Form` class has a couple of hooks you can use to add ``class``
attributes to required rows or to rows with errors: set the
:attr:`Form.error_css_class` and/or :attr:`Form.required_css_class`
attributes::
from django import forms
class ContactForm(forms.Form):
error_css_class = "error"
required_css_class = "required"
# ... and the rest of your fields here
Once you've done that, rows will be given ``"error"`` and/or ``"required"``
classes, as needed. The HTML will look something like:
.. code-block:: pycon
>>> f = ContactForm(data)
>>> print(f)
<div class="required"><label for="id_subject" class="required">Subject:</label> ...
<div class="required"><label for="id_message" class="required">Message:</label> ...
<div class="required"><label for="id_sender" class="required">Sender:</label> ...
<div><label for="id_cc_myself">Cc myself:</label> ...
>>> f["subject"].label_tag()
<label class="required" for="id_subject">Subject:</label>
>>> f["subject"].legend_tag()
<legend class="required" for="id_subject">Subject:</legend>
>>> f["subject"].label_tag(attrs={"class": "foo"})
<label for="id_subject" class="foo required">Subject:</label>
>>> f["subject"].legend_tag(attrs={"class": "foo"})
<legend for="id_subject" class="foo required">Subject:</legend>
.. _ref-forms-api-configuring-label:
Configuring form elements' HTML ``id`` attributes and ``<label>`` tags
----------------------------------------------------------------------
.. attribute:: Form.auto_id
By default, the form rendering methods include:
* HTML ``id`` attributes on the form elements.
* The corresponding ``<label>`` tags around the labels. An HTML ``<label>`` tag
designates which label text is associated with which form element. This small
enhancement makes forms more usable and more accessible to assistive devices.
It's always a good idea to use ``<label>`` tags.
The ``id`` attribute values are generated by prepending ``id_`` to the form
field names. This behavior is configurable, though, if you want to change the
``id`` convention or remove HTML ``id`` attributes and ``<label>`` tags
entirely.
Use the ``auto_id`` argument to the ``Form`` constructor to control the ``id``
and label behavior. This argument must be ``True``, ``False`` or a string.
If ``auto_id`` is ``False``, then the form output will not include ``<label>``
tags nor ``id`` attributes:
.. code-block:: pycon
>>> f = ContactForm(auto_id=False)
>>> print(f)
<div>Subject:<input type="text" name="subject" maxlength="100" required></div>
<div>Message:<textarea name="message" cols="40" rows="10" required></textarea></div>
<div>Sender:<input type="email" name="sender" required></div>
<div>Cc myself:<input type="checkbox" name="cc_myself"></div>
If ``auto_id`` is set to ``True``, then the form output *will* include
``<label>`` tags and will use the field name as its ``id`` for each form
field:
.. code-block:: pycon
>>> f = ContactForm(auto_id=True)
>>> print(f)
<div><label for="subject">Subject:</label><input type="text" name="subject" maxlength="100" required id="subject"></div>
<div><label for="message">Message:</label><textarea name="message" cols="40" rows="10" required id="message"></textarea></div>
<div><label for="sender">Sender:</label><input type="email" name="sender" required id="sender"></div>
<div><label for="cc_myself">Cc myself:</label><input type="checkbox" name="cc_myself" id="cc_myself"></div>
If ``auto_id`` is set to a string containing the format character ``'%s'``,
then the form output will include ``<label>`` tags, and will generate ``id``
attributes based on the format string. For example, for a format string
``'field_%s'``, a field named ``subject`` will get the ``id`` value
``'field_subject'``. Continuing our example:
.. code-block:: pycon
>>> f = ContactForm(auto_id="id_for_%s")
>>> print(f)
<div><label for="id_for_subject">Subject:</label><input type="text" name="subject" maxlength="100" required id="id_for_subject"></div>
<div><label for="id_for_message">Message:</label><textarea name="message" cols="40" rows="10" required id="id_for_message"></textarea></div>
<div><label for="id_for_sender">Sender:</label><input type="email" name="sender" required id="id_for_sender"></div>
<div><label for="id_for_cc_myself">Cc myself:</label><input type="checkbox" name="cc_myself" id="id_for_cc_myself"></div>
If ``auto_id`` is set to any other true value -- such as a string that doesn't
include ``%s`` -- then the library will act as if ``auto_id`` is ``True``.
By default, ``auto_id`` is set to the string ``'id_%s'``.
.. attribute:: Form.label_suffix
A translatable string (defaults to a colon (``:``) in English) that will be
appended after any label name when a form is rendered.
It's possible to customize that character, or omit it entirely, using the
``label_suffix`` parameter:
.. code-block:: pycon
>>> f = ContactForm(auto_id="id_for_%s", label_suffix="")
>>> print(f)
<div><label for="id_for_subject">Subject</label><input type="text" name="subject" maxlength="100" required id="id_for_subject"></div>
<div><label for="id_for_message">Message</label><textarea name="message" cols="40" rows="10" required id="id_for_message"></textarea></div>
<div><label for="id_for_sender">Sender</label><input type="email" name="sender" required id="id_for_sender"></div>
<div><label for="id_for_cc_myself">Cc myself</label><input type="checkbox" name="cc_myself" id="id_for_cc_myself"></div>
>>> f = ContactForm(auto_id="id_for_%s", label_suffix=" ->")
>>> print(f)
<div><label for="id_for_subject">Subject:</label><input type="text" name="subject" maxlength="100" required id="id_for_subject"></div>
<div><label for="id_for_message">Message -></label><textarea name="message" cols="40" rows="10" required id="id_for_message"></textarea></div>
<div><label for="id_for_sender">Sender -></label><input type="email" name="sender" required id="id_for_sender"></div>
<div><label for="id_for_cc_myself">Cc myself -></label><input type="checkbox" name="cc_myself" id="id_for_cc_myself"></div>
Note that the label suffix is added only if the last character of the
label isn't a punctuation character (in English, those are ``.``, ``!``, ``?``
or ``:``).
Fields can also define their own :attr:`~django.forms.Field.label_suffix`.
This will take precedence over :attr:`Form.label_suffix
<django.forms.Form.label_suffix>`. The suffix can also be overridden at runtime
using the ``label_suffix`` parameter to
:meth:`~django.forms.BoundField.label_tag`/
:meth:`~django.forms.BoundField.legend_tag`.
.. attribute:: Form.use_required_attribute
When set to ``True`` (the default), required form fields will have the
``required`` HTML attribute.
:doc:`Formsets </topics/forms/formsets>` instantiate forms with
``use_required_attribute=False`` to avoid incorrect browser validation when
adding and deleting forms from a formset.
Configuring the rendering of a form's widgets
---------------------------------------------
.. attribute:: Form.default_renderer
Specifies the :doc:`renderer <renderers>` to use for the form. Defaults to
``None`` which means to use the default renderer specified by the
:setting:`FORM_RENDERER` setting.
You can set this as a class attribute when declaring your form or use the
``renderer`` argument to ``Form.__init__()``. For example::
from django import forms
class MyForm(forms.Form):
default_renderer = MyRenderer()
or::
form = MyForm(renderer=MyRenderer())
Notes on field ordering
-----------------------
In the ``as_p()``, ``as_ul()`` and ``as_table()`` shortcuts, the fields are
displayed in the order in which you define them in your form class. For
example, in the ``ContactForm`` example, the fields are defined in the order
``subject``, ``message``, ``sender``, ``cc_myself``. To reorder the HTML
output, change the order in which those fields are listed in the class.
There are several other ways to customize the order:
.. attribute:: Form.field_order
By default ``Form.field_order=None``, which retains the order in which you
define the fields in your form class. If ``field_order`` is a list of field
names, the fields are ordered as specified by the list and remaining fields are
appended according to the default order. Unknown field names in the list are
ignored. This makes it possible to disable a field in a subclass by setting it
to ``None`` without having to redefine ordering.
You can also use the ``Form.field_order`` argument to a :class:`Form` to
override the field order. If a :class:`~django.forms.Form` defines
:attr:`~Form.field_order` *and* you include ``field_order`` when instantiating
the ``Form``, then the latter ``field_order`` will have precedence.
.. method:: Form.order_fields(field_order)
You may rearrange the fields any time using ``order_fields()`` with a list of
field names as in :attr:`~django.forms.Form.field_order`.
How errors are displayed
------------------------
If you render a bound ``Form`` object, the act of rendering will automatically
run the form's validation if it hasn't already happened, and the HTML output
will include the validation errors as a ``<ul class="errorlist">`` near the
field. The particular positioning of the error messages depends on the output
method you're using:
.. code-block:: pycon
>>> data = {
... "subject": "",
... "message": "Hi there",
... "sender": "invalid email address",
... "cc_myself": True,
... }
>>> f = ContactForm(data, auto_id=False)
>>> print(f)
<div>Subject:<ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="subject" maxlength="100" required></div>
<div>Message:<textarea name="message" cols="40" rows="10" required>Hi there</textarea></div>
<div>Sender:<ul class="errorlist"><li>Enter a valid email address.</li></ul><input type="email" name="sender" value="invalid email address" required></div>
<div>Cc myself:<input type="checkbox" name="cc_myself" checked></div>
.. _ref-forms-error-list-format:
Customizing the error list format
---------------------------------
.. class:: ErrorList(initlist=None, error_class=None, renderer=None)
By default, forms use ``django.forms.utils.ErrorList`` to format validation
errors. ``ErrorList`` is a list like object where ``initlist`` is the
list of errors. In addition this class has the following attributes and
methods.
.. attribute:: error_class
The CSS classes to be used when rendering the error list. Any provided
classes are added to the default ``errorlist`` class.
.. attribute:: renderer
Specifies the :doc:`renderer <renderers>` to use for ``ErrorList``.
Defaults to ``None`` which means to use the default renderer
specified by the :setting:`FORM_RENDERER` setting.
.. attribute:: template_name
The name of the template used when calling ``__str__`` or
:meth:`render`. By default this is
``'django/forms/errors/list/default.html'`` which is a proxy for the
``'ul.html'`` template.
.. attribute:: template_name_text
The name of the template used when calling :meth:`.as_text`. By default
this is ``'django/forms/errors/list/text.html'``. This template renders
the errors as a list of bullet points.
.. attribute:: template_name_ul
The name of the template used when calling :meth:`.as_ul`. By default
this is ``'django/forms/errors/list/ul.html'``. This template renders
the errors in ``<li>`` tags with a wrapping ``<ul>`` with the CSS
classes as defined by :attr:`.error_class`.
.. method:: get_context()
Return context for rendering of errors in a template.
The available context is:
* ``errors`` : A list of the errors.
* ``error_class`` : A string of CSS classes.
.. method:: render(template_name=None, context=None, renderer=None)
The render method is called by ``__str__`` as well as by the
:meth:`.as_ul` method.
All arguments are optional and will default to:
* ``template_name``: Value returned by :attr:`.template_name`
* ``context``: Value returned by :meth:`.get_context`
* ``renderer``: Value returned by :attr:`.renderer`
.. method:: as_text()
Renders the error list using the template defined by
:attr:`.template_name_text`.
.. method:: as_ul()
Renders the error list using the template defined by
:attr:`.template_name_ul`.
If you'd like to customize the rendering of errors this can be achieved by
overriding the :attr:`.template_name` attribute or more generally by
overriding the default template, see also
:ref:`overriding-built-in-form-templates`.
More granular output
====================
The ``as_p()``, ``as_ul()``, and ``as_table()`` methods are shortcuts --
they're not the only way a form object can be displayed.
.. class:: BoundField
Used to display HTML or access attributes for a single field of a
:class:`Form` instance.
The ``__str__()`` method of this object displays the HTML for this field.
To retrieve a single ``BoundField``, use dictionary lookup syntax on your form
using the field's name as the key:
.. code-block:: pycon
>>> form = ContactForm()
>>> print(form["subject"])
<input id="id_subject" type="text" name="subject" maxlength="100" required>
To retrieve all ``BoundField`` objects, iterate the form:
.. code-block:: pycon
>>> form = ContactForm()
>>> for boundfield in form:
... print(boundfield)
...
<input id="id_subject" type="text" name="subject" maxlength="100" required>
<input type="text" name="message" id="id_message" required>
<input type="email" name="sender" id="id_sender" required>
<input type="checkbox" name="cc_myself" id="id_cc_myself">
The field-specific output honors the form object's ``auto_id`` setting:
.. code-block:: pycon
>>> f = ContactForm(auto_id=False)
>>> print(f["message"])
<input type="text" name="message" required>
>>> f = ContactForm(auto_id="id_%s")
>>> print(f["message"])
<input type="text" name="message" id="id_message" required>
Attributes of ``BoundField``
----------------------------
.. attribute:: BoundField.auto_id
The HTML ID attribute for this ``BoundField``. Returns an empty string
if :attr:`Form.auto_id` is ``False``.
.. attribute:: BoundField.data
This property returns the data for this :class:`~django.forms.BoundField`
extracted by the widget's :meth:`~django.forms.Widget.value_from_datadict`
method, or ``None`` if it wasn't given:
.. code-block:: pycon
>>> unbound_form = ContactForm()
>>> print(unbound_form["subject"].data)
None
>>> bound_form = ContactForm(data={"subject": "My Subject"})
>>> print(bound_form["subject"].data)
My Subject
.. attribute:: BoundField.errors
A :ref:`list-like object <ref-forms-error-list-format>` that is displayed
as an HTML ``<ul class="errorlist">`` when printed:
.. code-block:: pycon
>>> data = {"subject": "hi", "message": "", "sender": "", "cc_myself": ""}
>>> f = ContactForm(data, auto_id=False)
>>> print(f["message"])
<input type="text" name="message" required>
>>> f["message"].errors
['This field is required.']
>>> print(f["message"].errors)
<ul class="errorlist"><li>This field is required.</li></ul>
>>> f["subject"].errors
[]
>>> print(f["subject"].errors)
>>> str(f["subject"].errors)
''
.. attribute:: BoundField.field
The form :class:`~django.forms.Field` instance from the form class that
this :class:`~django.forms.BoundField` wraps.
.. attribute:: BoundField.form
The :class:`~django.forms.Form` instance this :class:`~django.forms.BoundField`
is bound to.
.. attribute:: BoundField.help_text
The :attr:`~django.forms.Field.help_text` of the field.
.. attribute:: BoundField.html_name
The name that will be used in the widget's HTML ``name`` attribute. It takes
the form :attr:`~django.forms.Form.prefix` into account.
.. attribute:: BoundField.id_for_label
Use this property to render the ID of this field. For example, if you are
manually constructing a ``<label>`` in your template (despite the fact that
:meth:`~BoundField.label_tag`/:meth:`~BoundField.legend_tag` will do this
for you):
.. code-block:: html+django
<label for="{{ form.my_field.id_for_label }}">...</label>{{ my_field }}
By default, this will be the field's name prefixed by ``id_``
("``id_my_field``" for the example above). You may modify the ID by setting
:attr:`~django.forms.Widget.attrs` on the field's widget. For example,
declaring a field like this::
my_field = forms.CharField(widget=forms.TextInput(attrs={"id": "myFIELD"}))
and using the template above, would render something like:
.. code-block:: html
<label for="myFIELD">...</label><input id="myFIELD" type="text" name="my_field" required>
.. attribute:: BoundField.initial
Use :attr:`BoundField.initial` to retrieve initial data for a form field.
It retrieves the data from :attr:`Form.initial` if present, otherwise
trying :attr:`Field.initial`. Callable values are evaluated. See
:ref:`ref-forms-initial-form-values` for more examples.
:attr:`BoundField.initial` caches its return value, which is useful
especially when dealing with callables whose return values can change (e.g.
``datetime.now`` or ``uuid.uuid4``):
.. code-block:: pycon
>>> from datetime import datetime
>>> class DatedCommentForm(CommentForm):
... created = forms.DateTimeField(initial=datetime.now)
...
>>> f = DatedCommentForm()
>>> f["created"].initial
datetime.datetime(2021, 7, 27, 9, 5, 54)
>>> f["created"].initial
datetime.datetime(2021, 7, 27, 9, 5, 54)
Using :attr:`BoundField.initial` is recommended over
:meth:`~Form.get_initial_for_field()`.
.. attribute:: BoundField.is_hidden
Returns ``True`` if this :class:`~django.forms.BoundField`'s widget is
hidden.
.. attribute:: BoundField.label
The :attr:`~django.forms.Field.label` of the field. This is used in
:meth:`~BoundField.label_tag`/:meth:`~BoundField.legend_tag`.
.. attribute:: BoundField.name
The name of this field in the form:
.. code-block:: pycon
>>> f = ContactForm()
>>> print(f["subject"].name)
subject
>>> print(f["message"].name)
message
.. attribute:: BoundField.template_name
.. versionadded:: 5.0
The name of the template rendered with :meth:`.BoundField.as_field_group`.
A property returning the value of the
:attr:`~django.forms.Field.template_name` if set otherwise
:attr:`~django.forms.renderers.BaseRenderer.field_template_name`.
.. attribute:: BoundField.use_fieldset
Returns the value of this BoundField widget's ``use_fieldset`` attribute.
.. attribute:: BoundField.widget_type
Returns the lowercased class name of the wrapped field's widget, with any
trailing ``input`` or ``widget`` removed. This may be used when building
forms where the layout is dependent upon the widget type. For example:
.. code-block:: html+django
{% for field in form %}
{% if field.widget_type == 'checkbox' %}
# render one way
{% else %}
# render another way
{% endif %}
{% endfor %}
Methods of ``BoundField``
-------------------------
.. method:: BoundField.as_field_group()
.. versionadded:: 5.0
Renders the field using :meth:`.BoundField.render` with default values
which renders the ``BoundField``, including its label, help text and errors
using the template's :attr:`~django.forms.Field.template_name` if set
otherwise :attr:`~django.forms.renderers.BaseRenderer.field_template_name`
.. method:: BoundField.as_hidden(attrs=None, **kwargs)
Returns a string of HTML for representing this as an ``<input type="hidden">``.
``**kwargs`` are passed to :meth:`~django.forms.BoundField.as_widget`.
This method is primarily used internally. You should use a widget instead.
.. method:: BoundField.as_widget(widget=None, attrs=None, only_initial=False)
Renders the field by rendering the passed widget, adding any HTML
attributes passed as ``attrs``. If no widget is specified, then the
field's default widget will be used.
``only_initial`` is used by Django internals and should not be set
explicitly.
.. method:: BoundField.css_classes(extra_classes=None)
When you use Django's rendering shortcuts, CSS classes are used to
indicate required form fields or fields that contain errors. If you're
manually rendering a form, you can access these CSS classes using the
``css_classes`` method:
.. code-block:: pycon
>>> f = ContactForm(data={"message": ""})
>>> f["message"].css_classes()
'required'
If you want to provide some additional classes in addition to the
error and required classes that may be required, you can provide
those classes as an argument:
.. code-block:: pycon
>>> f = ContactForm(data={"message": ""})
>>> f["message"].css_classes("foo bar")
'foo bar required'
.. method:: BoundField.get_context()
.. versionadded:: 5.0
Return the template context for rendering the field. The available context
is ``field`` being the instance of the bound field.
.. method:: BoundField.label_tag(contents=None, attrs=None, label_suffix=None, tag=None)
Renders a label tag for the form field using the template specified by
:attr:`.Form.template_name_label`.
The available context is:
* ``field``: This instance of the :class:`BoundField`.
* ``contents``: By default a concatenated string of
:attr:`BoundField.label` and :attr:`Form.label_suffix` (or
:attr:`Field.label_suffix`, if set). This can be overridden by the
``contents`` and ``label_suffix`` arguments.
* ``attrs``: A ``dict`` containing ``for``,
:attr:`Form.required_css_class`, and ``id``. ``id`` is generated by the
field's widget ``attrs`` or :attr:`BoundField.auto_id`. Additional
attributes can be provided by the ``attrs`` argument.
* ``use_tag``: A boolean which is ``True`` if the label has an ``id``.
If ``False`` the default template omits the ``tag``.
* ``tag``: An optional string to customize the tag, defaults to ``label``.
.. tip::
In your template ``field`` is the instance of the ``BoundField``.
Therefore ``field.field`` accesses :attr:`BoundField.field` being
the field you declare, e.g. ``forms.CharField``.
To separately render the label tag of a form field, you can call its
``label_tag()`` method:
.. code-block:: pycon
>>> f = ContactForm(data={"message": ""})
>>> print(f["message"].label_tag())
<label for="id_message">Message:</label>
If you'd like to customize the rendering this can be achieved by overriding
the :attr:`.Form.template_name_label` attribute or more generally by
overriding the default template, see also
:ref:`overriding-built-in-form-templates`.
.. method:: BoundField.legend_tag(contents=None, attrs=None, label_suffix=None)
Calls :meth:`.label_tag` with ``tag='legend'`` to render the label with
``<legend>`` tags. This is useful when rendering radio and multiple
checkbox widgets where ``<legend>`` may be more appropriate than a
``<label>``.
.. method:: BoundField.render(template_name=None, context=None, renderer=None)
.. versionadded:: 5.0
The render method is called by ``as_field_group``. All arguments are
optional and default to:
* ``template_name``: :attr:`.BoundField.template_name`
* ``context``: Value returned by :meth:`.BoundField.get_context`
* ``renderer``: Value returned by :attr:`.Form.default_renderer`
By passing ``template_name`` you can customize the template used for just a
single call.
.. method:: BoundField.value()
Use this method to render the raw value of this field as it would be rendered
by a ``Widget``:
.. code-block:: pycon
>>> initial = {"subject": "welcome"}
>>> unbound_form = ContactForm(initial=initial)
>>> bound_form = ContactForm(data={"subject": "hi"}, initial=initial)
>>> print(unbound_form["subject"].value())
welcome
>>> print(bound_form["subject"].value())
hi
Customizing ``BoundField``
==========================
If you need to access some additional information about a form field in a
template and using a subclass of :class:`~django.forms.Field` isn't
sufficient, consider also customizing :class:`~django.forms.BoundField`.
A custom form field can override ``get_bound_field()``:
.. method:: Field.get_bound_field(form, field_name)
Takes an instance of :class:`~django.forms.Form` and the name of the field.
The return value will be used when accessing the field in a template. Most
likely it will be an instance of a subclass of
:class:`~django.forms.BoundField`.
If you have a ``GPSCoordinatesField``, for example, and want to be able to
access additional information about the coordinates in a template, this could
be implemented as follows::
class GPSCoordinatesBoundField(BoundField):
@property
def country(self):
"""
Return the country the coordinates lie in or None if it can't be
determined.
"""
value = self.value()
if value:
return get_country_from_coordinates(value)
else:
return None
class GPSCoordinatesField(Field):
def get_bound_field(self, form, field_name):
return GPSCoordinatesBoundField(form, self, field_name)
Now you can access the country in a template with
``{{ form.coordinates.country }}``.
.. _binding-uploaded-files:
Binding uploaded files to a form
================================
Dealing with forms that have ``FileField`` and ``ImageField`` fields
is a little more complicated than a normal form.
Firstly, in order to upload files, you'll need to make sure that your
``<form>`` element correctly defines the ``enctype`` as
``"multipart/form-data"``:
.. code-block:: html
<form enctype="multipart/form-data" method="post" action="/foo/">
Secondly, when you use the form, you need to bind the file data. File
data is handled separately to normal form data, so when your form
contains a ``FileField`` and ``ImageField``, you will need to specify
a second argument when you bind your form. So if we extend our
ContactForm to include an ``ImageField`` called ``mugshot``, we
need to bind the file data containing the mugshot image:
.. code-block:: pycon
# Bound form with an image field
>>> from django.core.files.uploadedfile import SimpleUploadedFile
>>> data = {
... "subject": "hello",
... "message": "Hi there",
... "sender": "foo@example.com",
... "cc_myself": True,
... }
>>> file_data = {"mugshot": SimpleUploadedFile("face.jpg", b"file data")}
>>> f = ContactFormWithMugshot(data, file_data)
In practice, you will usually specify ``request.FILES`` as the source
of file data (just like you use ``request.POST`` as the source of
form data):
.. code-block:: pycon
# Bound form with an image field, data from the request
>>> f = ContactFormWithMugshot(request.POST, request.FILES)
Constructing an unbound form is the same as always -- omit both form data *and*
file data:
.. code-block:: pycon
# Unbound form with an image field
>>> f = ContactFormWithMugshot()
Testing for multipart forms
---------------------------
.. method:: Form.is_multipart()
If you're writing reusable views or templates, you may not know ahead of time
whether your form is a multipart form or not. The ``is_multipart()`` method
tells you whether the form requires multipart encoding for submission:
.. code-block:: pycon
>>> f = ContactFormWithMugshot()
>>> f.is_multipart()
True
Here's an example of how you might use this in a template:
.. code-block:: html+django
{% if form.is_multipart %}
<form enctype="multipart/form-data" method="post" action="/foo/">
{% else %}
<form method="post" action="/foo/">
{% endif %}
{{ form }}
</form>
Subclassing forms
=================
If you have multiple ``Form`` classes that share fields, you can use
subclassing to remove redundancy.
When you subclass a custom ``Form`` class, the resulting subclass will
include all fields of the parent class(es), followed by the fields you define
in the subclass.
In this example, ``ContactFormWithPriority`` contains all the fields from
``ContactForm``, plus an additional field, ``priority``. The ``ContactForm``
fields are ordered first:
.. code-block:: pycon
>>> class ContactFormWithPriority(ContactForm):
... priority = forms.CharField()
...
>>> f = ContactFormWithPriority(auto_id=False)
>>> print(f)
<div>Subject:<input type="text" name="subject" maxlength="100" required></div>
<div>Message:<textarea name="message" cols="40" rows="10" required></textarea></div>
<div>Sender:<input type="email" name="sender" required></div>
<div>Cc myself:<input type="checkbox" name="cc_myself"></div>
<div>Priority:<input type="text" name="priority" required></div>
It's possible to subclass multiple forms, treating forms as mixins. In this
example, ``BeatleForm`` subclasses both ``PersonForm`` and ``InstrumentForm``
(in that order), and its field list includes the fields from the parent
classes:
.. code-block:: pycon
>>> from django import forms
>>> class PersonForm(forms.Form):
... first_name = forms.CharField()
... last_name = forms.CharField()
...
>>> class InstrumentForm(forms.Form):
... instrument = forms.CharField()
...
>>> class BeatleForm(InstrumentForm, PersonForm):
... haircut_type = forms.CharField()
...
>>> b = BeatleForm(auto_id=False)
>>> print(b)
<div>First name:<input type="text" name="first_name" required></div>
<div>Last name:<input type="text" name="last_name" required></div>
<div>Instrument:<input type="text" name="instrument" required></div>
<div>Haircut type:<input type="text" name="haircut_type" required></div>
It's possible to declaratively remove a ``Field`` inherited from a parent class
by setting the name of the field to ``None`` on the subclass. For example:
.. code-block:: pycon
>>> from django import forms
>>> class ParentForm(forms.Form):
... name = forms.CharField()
... age = forms.IntegerField()
...
>>> class ChildForm(ParentForm):
... name = None
...
>>> list(ChildForm().fields)
['age']
.. _form-prefix:
Prefixes for forms
==================
.. attribute:: Form.prefix
You can put several Django forms inside one ``<form>`` tag. To give each
``Form`` its own namespace, use the ``prefix`` keyword argument:
.. code-block:: pycon
>>> mother = PersonForm(prefix="mother")
>>> father = PersonForm(prefix="father")
>>> print(mother)
<div><label for="id_mother-first_name">First name:</label><input type="text" name="mother-first_name" required id="id_mother-first_name"></div>
<div><label for="id_mother-last_name">Last name:</label><input type="text" name="mother-last_name" required id="id_mother-last_name"></div>
>>> print(father)
<div><label for="id_father-first_name">First name:</label><input type="text" name="father-first_name" required id="id_father-first_name"></div>
<div><label for="id_father-last_name">Last name:</label><input type="text" name="father-last_name" required id="id_father-last_name"></div>
The prefix can also be specified on the form class:
.. code-block:: pycon
>>> class PersonForm(forms.Form):
... ...
... prefix = "person"
...
|