Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override default_error_messages on SlugRelatedField

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.

like image 841
mmedal Avatar asked Jan 27 '26 17:01

mmedal


2 Answers

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.

like image 165
AbrahamCoding Avatar answered Feb 01 '26 16:02

AbrahamCoding


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.

like image 35
mariodev Avatar answered Feb 01 '26 16:02

mariodev