You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/api-guide/fields.md
+48-1Lines changed: 48 additions & 1 deletion
Original file line number
Diff line number
Diff line change
@@ -453,7 +453,7 @@ If you want to create a custom field, you'll need to subclass `Field` and then o
453
453
454
454
The `.to_representation()` method is called to convert the initial datatype into a primitive, serializable datatype.
455
455
456
-
The `to_internal_value()` method is called to restore a primitive datatype into its internal python representation.
456
+
The `to_internal_value()` method is called to restore a primitive datatype into its internal python representation. This method should raise a `serializer.ValidationError` if the data is invalid.
457
457
458
458
Note that the `WritableField` class that was present in version 2.x no longer exists. You should subclass `Field` and override `to_internal_value()` if the field supports data input.
459
459
@@ -498,6 +498,53 @@ As an example, let's create a field that can be used represent the class name of
498
498
"""
499
499
return obj.__class__.__name__
500
500
501
+
#### Raising validation errors
502
+
503
+
Our `ColorField` class above currently does not perform any data validation.
504
+
To indicate invalid data, we should raise a `serializers.ValidationError`, like so:
505
+
506
+
def to_internal_value(self, data):
507
+
if not isinstance(data, six.text_type):
508
+
msg = 'Incorrect type. Expected a string, but got %s'
509
+
raise ValidationError(msg % type(data).__name__)
510
+
511
+
if not re.match(r'^rgb\([0-9]+,[0-9]+,[0-9]+\)$', data):
0 commit comments