From bf35906dc01f03ead9a5fd96a47c05c4ace95cff Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 3 Aug 2015 10:17:41 +0100 Subject: [PATCH] FilePathField subclassing from ChoiceField --- rest_framework/fields.py | 53 +++++++++++++--------------------------- 1 file changed, 17 insertions(+), 36 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index bff73dd2d..aa264b2aa 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -705,42 +705,6 @@ class IPAddressField(CharField): return super(IPAddressField, self).to_internal_value(data) -class FilePathField(CharField): - default_error_messages = { - 'invalid_choice': _('"{input}" is not a valid path choice.') - } - - def __init__(self, path, match=None, recursive=False, allow_files=True, - allow_folders=False, required=None, **kwargs): - super(FilePathField, self).__init__(**kwargs) - - # Defer to Django's FilePathField implmentation to get the - # valid set of choices. - field = DjangoFilePathField( - path, match=match, recursive=recursive, allow_files=allow_files, - allow_folders=allow_folders, required=required - ) - - self.choices = OrderedDict(field.choices) - self.choice_strings_to_values = dict([ - (six.text_type(key), key) for key in self.choices.keys() - ]) - - def to_internal_value(self, data): - if data == '' and self.allow_blank: - return '' - - try: - return self.choice_strings_to_values[six.text_type(data)] - except KeyError: - self.fail('invalid_choice', input=data) - - def to_representation(self, value): - if value in ('', None): - return value - return self.choice_strings_to_values[six.text_type(value)] - - # Number types... class IntegerField(Field): @@ -1215,6 +1179,23 @@ class MultipleChoiceField(ChoiceField): ]) +class FilePathField(ChoiceField): + default_error_messages = { + 'invalid_choice': _('"{input}" is not a valid path choice.') + } + + def __init__(self, path, match=None, recursive=False, allow_files=True, + allow_folders=False, required=None, **kwargs): + # Defer to Django's FilePathField implmentation to get the + # valid set of choices. + field = DjangoFilePathField( + path, match=match, recursive=recursive, allow_files=allow_files, + allow_folders=allow_folders, required=required + ) + kwargs['choices'] = field.choices + super(FilePathField, self).__init__(**kwargs) + + # File types... class FileField(Field):