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.
- [Django]-Install hstore extension for django tests
- [Django]-Django-Userena: adding extra non-null fields to a user's profile
- [Django]-Set image size limit and resize image if is needed
- [Django]-Model integrity check in django
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"}}}
- [Django]-Redirect to "next" after python-social-auth login
- [Django]-Django post_save and south migrations
- [Django]-Using Constants in Settings.py