Skip to content

[fields] Format error message only if params exist #6624

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 1, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions rest_framework/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,12 +239,12 @@ def get_error_detail(exc_info):
error_dict = exc_info.error_dict
except AttributeError:
return [
ErrorDetail(error.message % (error.params or ()),
ErrorDetail((error.message % error.params) if error.params else error.message,
code=error.code if error.code else code)
for error in exc_info.error_list]
return {
k: [
ErrorDetail(error.message % (error.params or ()),
ErrorDetail((error.message % error.params) if error.params else error.message,
code=error.code if error.code else code)
for error in errors
] for k, errors in error_dict.items()
Expand Down
23 changes: 21 additions & 2 deletions tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -2230,14 +2230,33 @@ class ExampleSerializer(serializers.Serializer):
password = serializers.CharField()

def validate_password(self, obj):
err = DjangoValidationError('exc_msg', code='exc_code')
err = DjangoValidationError(
'exc_msg %s', code='exc_code', params=('exc_param',),
)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is not related to the issue, but there was no test that actually used params.

if use_list:
err = DjangoValidationError([err])
raise err

serializer = ExampleSerializer(data={'password': 123})
serializer.is_valid()
assert serializer.errors == {'password': ['exc_msg']}
assert serializer.errors == {'password': ['exc_msg exc_param']}
assert serializer.errors['password'][0].code == 'exc_code'

@pytest.mark.parametrize('use_list', (False, True))
def test_validationerror_code_with_msg_including_percent(self, use_list):

class ExampleSerializer(serializers.Serializer):
password = serializers.CharField()

def validate_password(self, obj):
err = DjangoValidationError('exc_msg with %', code='exc_code')
if use_list:
err = DjangoValidationError([err])
raise err

serializer = ExampleSerializer(data={'password': 123})
serializer.is_valid()
assert serializer.errors == {'password': ['exc_msg with %']}
assert serializer.errors['password'][0].code == 'exc_code'

@pytest.mark.parametrize('code', (None, 'exc_code',))
Expand Down