Skip to content

Commit f02ef49

Browse files
authored
🐛 Restore default handling for omitted boolean form fields (#16605)
1 parent 69ddc2b commit f02ef49

13 files changed

Lines changed: 235 additions & 112 deletions

File tree

‎docs/en/docs/release-notes.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,12 @@ hide:
77

88
## Latest Changes
99

10+
Omitted `bool` and `bool | None` form fields now use their declared defaults or produce missing-field errors, consistent with other fields and Pydantic behavior. FastAPI no longer infers `False` for omitted booleans. This applies to individual form parameters, form models, and unions of form models.
11+
12+
Omitted boolean model fields are excluded from `model_dump(exclude_unset=True)`, and their defaults no longer count as submitted fields during union selection. Default factories and `validate_default` follow the usual rules.
13+
14+
For HTML checkboxes, declare a boolean with a default of `False`. See [Boolean Form Fields](https://fastapi.tiangolo.com/tutorial/request-forms/#boolean-form-fields).
15+
1016
## 0.161.1 (2026-10-22)
1117

1218
### Fixes

‎docs/en/docs/tutorial/request-form-models.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ You just need to declare a **Pydantic model** with the fields you want to receiv
2828

2929
**FastAPI** will **extract** the data for **each field** from the **form data** in the request and give you the Pydantic model you defined.
3030

31-
Boolean fields follow the same [omission rules](request-forms.md#boolean-form-fields) as individual form parameters.
31+
For [HTML checkboxes](request-forms.md#boolean-form-fields), declare boolean fields with a default of `False`.
3232

3333
## Check the Docs { #check-the-docs }
3434

‎docs/en/docs/tutorial/request-forms.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,9 +46,11 @@ To declare form bodies, you need to use `Form` explicitly, because without it th
4646

4747
## Boolean Form Fields { #boolean-form-fields }
4848

49-
Browsers omit unchecked checkboxes. **FastAPI** treats omitted `bool` and `bool | None` form fields as `False`, even when their default is `True` or `None`.
49+
Browsers omit unchecked checkboxes when submitting HTML forms. Declare a boolean form parameter with a default of `False` to receive `False` when unchecked:
5050

51-
For JSON requests and direct Pydantic validation, required fields and defaults work as usual.
51+
{* ../../docs_src/request_forms/tutorial002_an_py310.py hl[9] *}
52+
53+
A checked checkbox sends its value, which defaults to `"on"`. **FastAPI** accepts `"on"` as `True`.
5254

5355
## About "Form Fields" { #about-form-fields }
5456

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
from typing import Annotated
2+
3+
from fastapi import FastAPI, Form
4+
5+
app = FastAPI()
6+
7+
8+
@app.post("/preferences/")
9+
async def update_preferences(subscribe: Annotated[bool, Form()] = False):
10+
return {"subscribe": subscribe}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
from fastapi import FastAPI, Form
2+
3+
app = FastAPI()
4+
5+
6+
@app.post("/preferences/")
7+
async def update_preferences(subscribe: bool = Form(default=False)):
8+
return {"subscribe": subscribe}

‎fastapi/dependencies/utils.py‎

Lines changed: 3 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1071,26 +1071,9 @@ def _extract_form_items(
10711071
field_aliases: set[str] = set()
10721072

10731073
for field in body_fields:
1074-
validation_alias = field.field_info.validation_alias
1075-
has_alias_path = isinstance(validation_alias, AliasPath) or (
1076-
isinstance(validation_alias, AliasChoices)
1077-
and any(
1078-
isinstance(choice, AliasPath) for choice in validation_alias.choices
1079-
)
1080-
)
1081-
aliases = [alias for alias, _ in _get_param_aliases(field)]
1082-
# Interpret missing boolean form fields as unchecked HTML checkboxes.
1083-
infer_false_if_missing = (
1084-
not has_alias_path
1085-
and field.field_info.annotation in (bool, bool | None)
1086-
and not any(alias in received_body for alias in aliases)
1087-
)
1088-
for alias in aliases:
1074+
for alias, _ in _get_param_aliases(field):
10891075
field_aliases.add(alias)
1090-
if infer_false_if_missing:
1091-
value: Any = False
1092-
else:
1093-
value = _get_multidict_value(field, received_body, alias=alias)
1076+
value = _get_multidict_value(field, received_body, alias=alias)
10941077
if value is not Undefined:
10951078
yield alias, value, field
10961079
# Leave later aliases unchanged for other fields or extra validation.
@@ -1141,7 +1124,7 @@ def _is_form_model_supplied(
11411124
model: type[BaseModel],
11421125
received_body: FormData,
11431126
) -> bool:
1144-
# Check raw keys before empty fields are removed or checkboxes inferred.
1127+
# Check raw keys before empty fields are removed.
11451128
own_names = {
11461129
alias
11471130
for item in get_cached_model_fields(model)

‎tests/test_forms_multiple_models.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,7 @@ def submit_dependency(
232232
assert models["Preferences"]["additionalProperties"] is False
233233

234234

235-
def test_model_defaults_checkboxes_and_validators_are_independent():
235+
def test_model_defaults_and_validators_are_independent():
236236
app = FastAPI()
237237
inputs = []
238238

@@ -274,9 +274,9 @@ def submit(
274274
response = client.post("/")
275275
assert response.status_code == 200, response.text
276276
assert response.json() == {
277-
"settings": {"label": "default", "enabled": False, "tags": []},
277+
"settings": {"label": "default", "enabled": True, "tags": []},
278278
"other": {"label": "other", "enabled": "other"},
279-
"fields_set": ["enabled"],
279+
"fields_set": [],
280280
"other_fields_set": [],
281281
}
282282
response = client.post(

‎tests/test_forms_multiple_unions.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ class Person(BaseModel):
1818
kind: Literal["person"] = Field(alias="contact_type")
1919
name: str
2020
tags: list[str] = Field(default_factory=list)
21-
enabled: bool = True
21+
enabled: bool = False
2222

2323

2424
class Company(BaseModel):
@@ -704,7 +704,7 @@ def test_json_and_original_model_schemas_are_unchanged():
704704
json={"contact": {"contact_type": "person", "name": "Rick"}, "token": "secret"},
705705
)
706706
assert response.status_code == 200, response.text
707-
assert response.json()["enabled"] is True
707+
assert response.json()["enabled"] is False
708708
schemas = app.openapi()["components"]["schemas"]
709709
assert set(schemas["Person"]["properties"]) == {
710710
"contact_type",

‎tests/test_forms_optional_models.py‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ class Profile(BaseModel):
2222
name: str
2323
age: int
2424
tags: list[str] = Field(default_factory=list)
25-
enabled: bool = True
25+
enabled: bool = False
2626

2727
@app.post("/")
2828
def submit(profile: Annotated[Profile | None, Form()] = None):
@@ -114,7 +114,7 @@ class Profile(BaseModel):
114114
name: str
115115
age: int
116116
tags: list[str] = Field(default_factory=list)
117-
enabled: bool = True
117+
enabled: bool = False
118118

119119
@app.post("/")
120120
def submit(
@@ -176,7 +176,7 @@ class Profile(BaseModel):
176176
name: str
177177
age: int
178178
tags: list[str] = Field(default_factory=list)
179-
enabled: bool = True
179+
enabled: bool = False
180180

181181
@app.post("/")
182182
def submit(profile: Annotated[Profile | None, Form()] = None):
@@ -224,7 +224,7 @@ class Profile(BaseModel):
224224
name: str
225225
age: int
226226
tags: list[str] = Field(default_factory=list)
227-
enabled: bool = True
227+
enabled: bool = False
228228

229229
@app.post("/")
230230
def submit(
@@ -276,7 +276,7 @@ def test_unknown_fields_and_sibling_models(extra, required_name):
276276
class Profile(BaseModel):
277277
model_config = ConfigDict(extra=extra)
278278
name: str = Field() if required_name else Field("default")
279-
enabled: bool = True
279+
enabled: bool = False
280280

281281
class Credentials(BaseModel):
282282
token: str
@@ -458,7 +458,7 @@ def validated_default(
458458
calls.clear()
459459
response = client.post("/factory", data={"name": "submitted"})
460460
assert response.status_code == 200, response.text
461-
assert response.json()["enabled"] is False
461+
assert response.json()["enabled"] is True
462462
assert calls == ["submitted"]
463463
calls.clear()
464464
response = client.post("/validated-default")

‎tests/test_forms_optional_unions.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
class TextForm(BaseModel):
2020
kind: Literal["text"]
2121
value: str
22-
enabled: bool = True
22+
enabled: bool = False
2323

2424

2525
class ListForm(BaseModel):
@@ -372,7 +372,7 @@ def read_validated_default(
372372
calls.clear()
373373
response = client.post("/factory", data={"kind": "defaults"})
374374
assert response.status_code == 200, response.text
375-
assert response.json() == {"kind": "defaults", "tags": [], "enabled": False}
375+
assert response.json() == {"kind": "defaults", "tags": [], "enabled": True}
376376
assert calls == ["validated"]
377377
calls.clear()
378378
response = client.post("/validated-default")

0 commit comments

Comments
 (0)