Skip to content

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

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

LindseyZ1205 wants to merge 1 commit 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.

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

None yet

Development

Successfully merging this pull request may close these issues.

1 participant