diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 799dd94f9..1c6425596 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -1480,6 +1480,7 @@ class FilePathField(ChoiceField): allow_folders=allow_folders, required=required ) kwargs['choices'] = field.choices + kwargs['required'] = required super().__init__(**kwargs) diff --git a/tests/test_fields.py b/tests/test_fields.py index 5fd075d40..512f3f789 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -15,7 +15,8 @@ from django.utils.timezone import activate, deactivate, override import rest_framework from rest_framework import exceptions, serializers from rest_framework.fields import ( - BuiltinSignatureError, DjangoImageField, is_simple_callable + BuiltinSignatureError, DjangoImageField, SkipField, empty, + is_simple_callable ) from tests.models import UUIDForeignKeyTarget @@ -2390,6 +2391,21 @@ class TestFileFieldContext: assert value == 'http://example.com/example.txt' +# Tests for FilePathField. +# -------------------- + +class TestFilePathFieldRequired: + def test_required_passed_to_both_django_file_path_field_and_base(self): + field = serializers.FilePathField( + path=os.path.abspath(os.path.dirname(__file__)), + required=False, + ) + assert "" in field.choices # Django adds empty choice if not required + assert field.required is False + with pytest.raises(SkipField): + field.run_validation(empty) + + # Tests for SerializerMethodField. # --------------------------------