Skip to content

Don't propagate model BooleanField defaults to serializer fields - #10115

Open
LindseyZ1205 wants to merge 4 commits into
encode:mainfrom
LindseyZ1205:fix/model-boolean-default-html
Open

LindseyZ1205 wants to merge 4 commits into
encode:mainfrom
LindseyZ1205:fix/model-boolean-default-html

Conversation

@LindseyZ1205

Copy link
Copy Markdown
Contributor

Description

refs #9997

Since #9997, ModelSerializer gives the field for a model BooleanField(default=True) a default=True. A BooleanField with a default reads a value that is missing from HTML form input as that default, and an HTML form leaves out an unchecked checkbox. So an HTML form can no longer set such a field to False:

class Setting(models.Model):
    name = models.CharField(max_length=20)
    enabled = models.BooleanField(default=True)


class SettingSerializer(serializers.ModelSerializer):
    class Meta:
        model = Setting
        fields = ['name', 'enabled']


serializer = SettingSerializer(data=QueryDict('name=x'))  # "enabled" left unchecked
serializer.is_valid()
serializer.validated_data  # {'name': 'x', 'enabled': True}, and {'name': 'x', 'enabled': False} before #9997

Through a ModelViewSet, a multipart PUT with the box unchecked leaves the stored value True. With a callable default, the same form fails with "Must be a valid boolean.", and a BooleanField(null=True, default=False) gets False instead of None.

The BooleanField docs also say that an omitted value in HTML form input counts as False, "even if it has a default=True option specified".

This skips the model default for boolean fields, as for relational fields, so they behave as they did before #9997. JSON input that leaves the field out still gets the model default when the instance is saved. Serializer BooleanFields declared with an explicit default are unchanged.

The new test fails on main and passes with this change. The full test suite passes on Django 6.1.2 and Django main.

Since encode#9997, the `ModelSerializer` field for a `BooleanField(default=True)`
gets `default=True`. A `BooleanField` with a default reads a value missing
from HTML form input as that default, and HTML forms leave out unchecked
checkboxes, so a form could no longer set the field to `False`: an
unchecked box was saved as `True`. With a callable default, the form
failed with "Must be a valid boolean.", and a `null=True` field got its
default instead of `None`.

Skip the default for boolean model fields, as for relational ones, so
these fields behave as they did before encode#9997.

@browniebroke browniebroke left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the fix, but I think we need a bit more test coverage as I'm not convinced we fixed all the use cases:

  • Declaring a BooleanField(default=True) on a plain Serializer
  • Custom model field mapped to serializers.BooleanField
  • Full JSON PUT omitting the boolean field

Comment thread docs/api-guide/fields.md Outdated
The `default` is not applied during partial update operations. In the partial update case only fields that are provided in the incoming data will have a validated value returned.

If you're using [Model Serializer](https://www.django-rest-framework.org/api-guide/serializers/#modelserializer) and the corresponding `Model` field declares a `default`, it will be used as the serializer field default. This does not apply to relational fields such as `ForeignKey`: a model default on a relational field is expressed as a primary key value rather than a model instance, so it is not propagated and only causes the generated serializer field to be not required.
If you're using [Model Serializer](https://www.django-rest-framework.org/api-guide/serializers/#modelserializer) and the corresponding `Model` field declares a `default`, it will be used as the serializer field default. This does not apply to relational fields such as `ForeignKey`: a model default on a relational field is expressed as a primary key value rather than a model instance, so it is not propagated and only causes the generated serializer field to be not required. Nor does it apply to `BooleanField`: HTML forms leave out unchecked checkboxes, so with the model default, a form could not set the field to `False`.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I find that the whole paragraph reads a bit weird, I think it's mainly down to the construct "This does not apply to... [long sentence]. Nor..."

How about:

This does not apply to BooleanField or relational fields such as ForeignKey. HTML forms leave out unchecked checkboxes, so with the BooleanField model default, a form could not set the field to False. A model default on a relational field is expressed as a primary key value rather than a model instance, so it is not propagated and only causes the generated serializer field to be not required

Not sure if my suggestion is the best way to phrase it either...

@auvipy
auvipy self-requested a review November 24, 2026 15:12
@auvipy

auvipy commented Nov 24, 2026

Copy link
Copy Markdown
Collaborator

@M2004GV it would be great if you try and review this as well

Check the serializer field class in `build_standard_field()`, instead of
the model field class in `get_field_kwargs()`, so that a custom model
field mapped to `BooleanField` doesn't get the model default either.

Also test that a `BooleanField(default=True)` declared on a plain
`Serializer` still uses its default for a missing HTML value, and that a
full JSON update leaving a boolean field out keeps its value. Reword the
docs as suggested in the review.
@M2004GV

M2004GV commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

Hi,

I tested the same scenarios through an actual ModelViewSet, using APIClient with JSON and multipart requests, against the commit before #9997, current main, and this PR.

The latest commit addresses the cases raised in the review: the HTML checkbox case is fixed, and the full test suite passes on this branch in the two environments I tested (Python 3.12/Django 6.1 and Python 3.10/Django 5.2).

However, the problem is wider than BooleanField, which is where @browniebroke's point about full JSON PUT requests leads.

On current main, a full PUT that omits a field with a model default overwrites its existing database value with that default. I reproduced this with CharField, IntegerField, DecimalField, choices, UUIDField, DateField, TimeField, DurationField and other field types. Callable defaults are regenerated (e.g. uuid4 and timezone.now), while JSONField(default=dict) can clear existing data.

Before #9997, these values were preserved. With this PR, omitted booleans are preserved again, but the other field types are still overwritten.

I also found an important historical precedent that I should have caught before submitting #9997:

The current behavior appears to reintroduce the same regression. On this branch, both expectations now sit side by side in tests/test_model_serializer.py: test_default_value_used_on_full_update (introduced in #9997) asserts that a full update resets an omitted IntegerField to its model default, while the new test_full_update_leaves_omitted_boolean_field_unchanged asserts that an omitted boolean is preserved.

Before proposing a fix, could the maintainers clarify the intended contract: should model defaults be applied when a field is omitted during a full update?

Separately, I noticed that the BooleanField documentation says an omitted checkbox evaluates to False even when default=True is specified.

@auvipy auvipy added the Bug label Nov 26, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Development

Successfully merging this pull request may close these issues.

4 participants