Skip to content

Commit

Permalink
fix: Only set False to clear FileFields when updating an instance (#601)
Browse files Browse the repository at this point in the history
  • Loading branch information
bellini666 authored Jul 24, 2024
1 parent 6dc6be9 commit 97743cf
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
5 changes: 3 additions & 2 deletions strawberry_django/mutations/resolvers.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,10 +248,11 @@ def prepare_create_update(
# Dont use these, fallback to model defaults.
direct_field_value = False
elif isinstance(field, models.FileField):
if value is None:
if value is None and instance.pk is not None:
# We want to reset the file field value when None was passed in the
# input, but `FileField.save_form_data` ignores None values. In that
# case we manually pass False which clears the file.
# case we manually pass False which clears the file
# (but only if the instance is already saved and we are updating it)
value = False # noqa: PLW2901
elif isinstance(field, (ManyToManyField, ForeignObjectRel)):
# m2m will be processed later
Expand Down
24 changes: 24 additions & 0 deletions tests/mutations/test_mutations.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,30 @@ def test_create_with_optional_file(mutation):
}


def test_create_with_optional_file_when_not_setting_it(mutation):
result = mutation(
"""\
CreateFruit($picture: Upload) {
createFruit(data: { name: "strawberry", picture: $picture }) {
id
name
picture {
name
}
}
}
""",
variable_values={"picture": None},
)

assert not result.errors
assert result.data["createFruit"] == {
"id": "1",
"name": "strawberry",
"picture": None,
}


def test_update_with_optional_file_when_unsetting_it(mutation):
fname = "test_update_with_optional_file.png"
upload = prep_image(fname)
Expand Down

0 comments on commit 97743cf

Please sign in to comment.