From the django-rest-framework documentation:
Each serializer field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted:
- error_messages - A dictionary of error codes to error messages.
I have attempted to override the "does_not_exist" error message in a SlugRelatedField like so:
example = SlugRelatedField(slug_field='label', error_messages={"does_not_exist": "Some custom error message."})
and receive the error:
not all arguments converted during string formatting
Any tips on how to proceed would be much appreciated.
I think django-rest-framework has changed how this works since this question was asked.
Using DRF version 3.8.2, the default error messages for SlugRelatedField are now:
default_error_messages = {
'does_not_exist': _('Object with {slug_name}={value} does not exist.'),
'invalid': _('Invalid value.'),
}
I was able to successfully override the does_not_exist error simply by:
field = SlugRelatedField(
error_messages={
'does_not_exist': 'Foo error field={value} does not exist.',
}
)
Note how I'm only using one of the values DRF inserts into the string - value, and I'm not using slug_name. This works fine.
The error message is rendered the following way:
raise ValidationError(self.error_messages['does_not_exist'] %
(self.slug_field, smart_text(data)))
So it forces you to include two %s placeholders.
This is the default:
'does_not_exist': _("Object with %s=%s does not exist."),
If you want to omit the %s arguments, then there's no other way except for overriding the whole from_native.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With