Reputation: 115
When getting a ValueError from a ForeignKey field in Django, the exception returns the response "Field ... expected a a number but got ..." using the field name. I'd like to change this exception to use the verbose_name if it exists, and the field name if it does not. How can I override this exception for all ForeignKey fields?
Line 1818 in https://github.com/django/django/blob/main/django/db/models/fields/__init__.py
def get_prep_value(self, value):
value = super().get_prep_value(value)
if value is None:
return None
try:
return int(value)
except (TypeError, ValueError) as e:
raise e.__class__(
"Field '%s' expected a number but got %r." % (self.name, value),
) from e
Upvotes: 0
Views: 748
Reputation: 115
I ended up getting this custom error message to work by overriding both the IntegerField and AutoField classes.
class CustomIntegerField(models.Field):
def get_prep_value(self, value):
value = super().get_prep_value(value)
if value is None:
return None
try:
return int(value)
except (TypeError, ValueError) as e:
field_name = self.name
if self.verbose_name:
field_name = self.verbose_name
raise e.__class__("Custom Error Message") from e
class CustomAutoField(AutoFieldMixin, CustomIntegerField, metaclass=AutoFieldMeta):
...
Upvotes: 2