There is a Django field type for storing values of MyType.
from django.core.exceptions import ValidationError
from django.db import models
class MyTypeField(models.Field):
__metaclass__ = models.SubfieldBase
def db_type(self, connection):
return "text"
def to_python(self, value):
if isinstance(value, basestring):
try:
value = MyType.deserialize(value)
except ParseError, e:
raise ValidationError("Invalid format: "+str(e))
assert isinstance(value, MyType)
return value
def get_prep_value(self, value):
if not isinstance(value, MyType):
raise ValidationError("Not MyType")
return value.serialize()
I am trying to use fields of this type on an admin page of a model. Everything works nice if a user enters a valid value in the field. But if the entered value is invalid, the ValidationError is not caught (you get error 500, or a stack trace if debug is enabled)
Instead I want to see the form with a message “Invalid format” near the field (just like if you enter an invalid date or number). How to modify the field class to get validation errors in a correct place.
Quoting from http://docs.djangoproject.com/en/1.2/howto/custom-model-fields/#modelforms-and-custom-fields
So a ValidationError will never be caught at this point.
to_pythonis also called when populating a new instance of your model from the database, which is outside the form validation context.So you have to move your validation into a formfield.