[Django]-Override default_error_messages on SlugRelatedField

1👍

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.

8👍

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.

0👍

For those who want to override the sane error but in DRF ModelSerializer.
Just look at that: my case where field promo_code is Fk to another model, to override does_not_exist error we schould do the following:

    class Meta:
        model = models.ActivePromoCode
        fields = ('promo_code', )
        extra_kwargs = {"promo_code": {"error_messages": {"does_not_exist": "promocode_not_found"}}}

Leave a comment