diff --git a/strawberry_django/mutations/resolvers.py b/strawberry_django/mutations/resolvers.py index 928804c6..9e09d3d2 100644 --- a/strawberry_django/mutations/resolvers.py +++ b/strawberry_django/mutations/resolvers.py @@ -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 diff --git a/tests/mutations/test_mutations.py b/tests/mutations/test_mutations.py index a3c6a259..9acb3b99 100644 --- a/tests/mutations/test_mutations.py +++ b/tests/mutations/test_mutations.py @@ -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)