Debian Codegraph @

docs/api-guide/validators.md

raw
1 ---
2 source:
3 - validators.py
4 ---
5
6 # Validators
7
8 > Validators can be useful for reusing validation logic between different types of fields.
9 >
10 > — [Django documentation][cite]
11
12 Most of the time you're dealing with validation in REST framework you'll simply be relying on the default field validation, or writing explicit validation methods on serializer or field classes.
13
14 However, sometimes you'll want to place your validation logic into reusable components, so that it can easily be reused throughout your codebase. This can be achieved by using validator functions and validator classes.
15
16 ## Validation in REST framework
17
18 Validation in Django REST framework serializers is handled a little differently to how validation works in Django's `ModelForm` class.
19
20 With `ModelForm` the validation is performed partially on the form, and partially on the model instance. With REST framework the validation is performed entirely on the serializer class. This is advantageous for the following reasons:
21
22 * It introduces a proper separation of concerns, making your code behavior more obvious.
23 * It is easy to switch between using shortcut `ModelSerializer` classes and using explicit `Serializer` classes. Any validation behavior being used for `ModelSerializer` is simple to replicate.
24 * Printing the `repr` of a serializer instance will show you exactly what validation rules it applies. There's no extra hidden validation behavior being called on the model instance.
25
26 When you're using `ModelSerializer` all of this is handled automatically for you. If you want to drop down to using `Serializer` classes instead, then you need to define the validation rules explicitly.
27
28 ### Example
29
30 As an example of how REST framework uses explicit validation, we'll take a simple model class that has a field with a uniqueness constraint.
31
32 class CustomerReportRecord(models.Model):
33 time_raised = models.DateTimeField(default=timezone.now, editable=False)
34 reference = models.CharField(unique=True, max_length=20)
35 description = models.TextField()
36
37 Here's a basic `ModelSerializer` that we can use for creating or updating instances of `CustomerReportRecord`:
38
39 class CustomerReportSerializer(serializers.ModelSerializer):
40 class Meta:
41 model = CustomerReportRecord
42
43 If we open up the Django shell using `manage.py shell` we can now
44
45 >>> from project.example.serializers import CustomerReportSerializer
46 >>> serializer = CustomerReportSerializer()
47 >>> print(repr(serializer))
48 CustomerReportSerializer():
49 id = IntegerField(label='ID', read_only=True)
50 time_raised = DateTimeField(read_only=True)
51 reference = CharField(max_length=20, validators=[UniqueValidator(queryset=CustomerReportRecord.objects.all())])
52 description = CharField(style={'type': 'textarea'})
53
54 The interesting bit here is the `reference` field. We can see that the uniqueness constraint is being explicitly enforced by a validator on the serializer field.
55
56 Because of this more explicit style REST framework includes a few validator classes that are not available in core Django. These classes are detailed below. REST framework validators, like their Django counterparts, implement the `__eq__` method, allowing you to compare instances for equality.
57
58 ---
59
60 ## UniqueValidator
61
62 This validator can be used to enforce the `unique=True` constraint on model fields.
63 It takes a single required argument, and an optional `messages` argument:
64
65 * `queryset` *required* - This is the queryset against which uniqueness should be enforced.
66 * `message` - The error message that should be used when validation fails.
67 * `lookup` - The lookup used to find an existing instance with the value being validated. Defaults to `'exact'`.
68
69 This validator should be applied to *serializer fields*, like so:
70
71 from rest_framework.validators import UniqueValidator
72
73 slug = SlugField(
74 max_length=100,
75 validators=[UniqueValidator(queryset=BlogPost.objects.all())]
76 )
77
78 ## UniqueTogetherValidator
79
80 This validator can be used to enforce `unique_together` constraints on model instances.
81 It has two required arguments, and a single optional `messages` argument:
82
83 * `queryset` *required* - This is the queryset against which uniqueness should be enforced.
84 * `fields` *required* - A list or tuple of field names which should make a unique set. These must exist as fields on the serializer class.
85 * `message` - The error message that should be used when validation fails.
86
87 The validator should be applied to *serializer classes*, like so:
88
89 from rest_framework.validators import UniqueTogetherValidator
90
91 class ExampleSerializer(serializers.Serializer):
92 # ...
93 class Meta:
94 # ToDo items belong to a parent list, and have an ordering defined
95 # by the 'position' field. No two items in a given list may share
96 # the same position.
97 validators = [
98 UniqueTogetherValidator(
99 queryset=ToDoItem.objects.all(),
100 fields=['list', 'position']
101 )
102 ]
103
104 !!! note
105 The `UniqueTogetherValidator` class always imposes an implicit constraint that all the fields it applies to are always treated as required. Fields with `default` values are an exception to this as they always supply a value even when omitted from user input.
106
107 ## UniqueForDateValidator
108
109 ## UniqueForMonthValidator
110
111 ## UniqueForYearValidator
112
113 These validators can be used to enforce the `unique_for_date`, `unique_for_month` and `unique_for_year` constraints on model instances. They take the following arguments:
114
115 * `queryset` *required* - This is the queryset against which uniqueness should be enforced.
116 * `field` *required* - A field name against which uniqueness in the given date range will be validated. This must exist as a field on the serializer class.
117 * `date_field` *required* - A field name which will be used to determine date range for the uniqueness constrain. This must exist as a field on the serializer class.
118 * `message` - The error message that should be used when validation fails.
119
120 The validator should be applied to *serializer classes*, like so:
121
122 from rest_framework.validators import UniqueForYearValidator
123
124 class ExampleSerializer(serializers.Serializer):
125 # ...
126 class Meta:
127 # Blog posts should have a slug that is unique for the current year.
128 validators = [
129 UniqueForYearValidator(
130 queryset=BlogPostItem.objects.all(),
131 field='slug',
132 date_field='published'
133 )
134 ]
135
136 The date field that is used for the validation is always required to be present on the serializer class. You can't simply rely on a model class `default=...`, because the value being used for the default wouldn't be generated until after the validation has run.
137
138 There are a couple of styles you may want to use for this depending on how you want your API to behave. If you're using `ModelSerializer` you'll probably simply rely on the defaults that REST framework generates for you, but if you are using `Serializer` or simply want more explicit control, use on of the styles demonstrated below.
139
140 ### Using with a writable date field.
141
142 If you want the date field to be writable the only thing worth noting is that you should ensure that it is always available in the input data, either by setting a `default` argument, or by setting `required=True`.
143
144 published = serializers.DateTimeField(required=True)
145
146 ### Using with a read-only date field.
147
148 If you want the date field to be visible, but not editable by the user, then set `read_only=True` and additionally set a `default=...` argument.
149
150 published = serializers.DateTimeField(read_only=True, default=timezone.now)
151
152 ### Using with a hidden date field.
153
154 If you want the date field to be entirely hidden from the user, then use `HiddenField`. This field type does not accept user input, but instead always returns its default value to the `validated_data` in the serializer.
155
156 published = serializers.HiddenField(default=timezone.now)
157
158 !!! note
159 The `UniqueFor<Range>Validator` classes impose an implicit constraint that the fields they are applied to are always treated as required. Fields with `default` values are an exception to this as they always supply a value even when omitted from user input.
160
161 !!! note
162 `HiddenField()` does not appear in `partial=True` serializer (when making `PATCH` request).
163
164 ## Advanced field defaults
165
166 Validators that are applied across multiple fields in the serializer can sometimes require a field input that should not be provided by the API client, but that *is* available as input to the validator.
167 For this purposes use `HiddenField`. This field will be present in `validated_data` but *will not* be used in the serializer output representation.
168
169 !!! note
170 Using a `read_only=True` field is excluded from writable fields so it won't use a `default=…` argument. Look [3.8 announcement](https://www.django-rest-framework.org/community/3.8-announcement/#altered-the-behavior-of-read_only-plus-default-on-field).
171
172 REST framework includes a couple of defaults that may be useful in this context.
173
174 ### CurrentUserDefault
175
176 A default class that can be used to represent the current user. In order to use this, the 'request' must have been provided as part of the context dictionary when instantiating the serializer.
177
178 owner = serializers.HiddenField(
179 default=serializers.CurrentUserDefault()
180 )
181
182 ### CreateOnlyDefault
183
184 A default class that can be used to *only set a default argument during create operations*. During updates the field is omitted.
185
186 It takes a single argument, which is the default value or callable that should be used during create operations.
187
188 created_at = serializers.DateTimeField(
189 default=serializers.CreateOnlyDefault(timezone.now)
190 )
191
192 ---
193
194 ## Limitations of validators
195
196 There are some ambiguous cases where you'll need to instead handle validation
197 explicitly, rather than relying on the default serializer classes that
198 `ModelSerializer` generates.
199
200 In these cases you may want to disable the automatically generated validators,
201 by specifying an empty list for the serializer `Meta.validators` attribute.
202
203 ### Optional fields
204
205 By default "unique together" validation enforces that all fields be
206 `required=True`. In some cases, you might want to explicit apply
207 `required=False` to one of the fields, in which case the desired behavior
208 of the validation is ambiguous.
209
210 In this case you will typically need to exclude the validator from the
211 serializer class, and instead write any validation logic explicitly, either
212 in the `.validate()` method, or else in the view.
213
214 For example:
215
216 class BillingRecordSerializer(serializers.ModelSerializer):
217 def validate(self, attrs):
218 # Apply custom validation either here, or in the view.
219
220 class Meta:
221 fields = ['client', 'date', 'amount']
222 extra_kwargs = {'client': {'required': False}}
223 validators = [] # Remove a default "unique together" constraint.
224
225 ### Updating nested serializers
226
227 When applying an update to an existing instance, uniqueness validators will
228 exclude the current instance from the uniqueness check. The current instance
229 is available in the context of the uniqueness check, because it exists as
230 an attribute on the serializer, having initially been passed using
231 `instance=...` when instantiating the serializer.
232
233 In the case of update operations on *nested* serializers there's no way of
234 applying this exclusion, because the instance is not available.
235
236 Again, you'll probably want to explicitly remove the validator from the
237 serializer class, and write the code for the validation constraint
238 explicitly, in a `.validate()` method, or in the view.
239
240 ### Debugging complex cases
241
242 If you're not sure exactly what behavior a `ModelSerializer` class will
243 generate it is usually a good idea to run `manage.py shell`, and print
244 an instance of the serializer, so that you can inspect the fields and
245 validators that it automatically generates for you.
246
247 >>> serializer = MyComplexModelSerializer()
248 >>> print(serializer)
249 class MyComplexModelSerializer:
250 my_fields = ...
251
252 Also keep in mind that with complex cases it can often be better to explicitly
253 define your serializer classes, rather than relying on the default
254 `ModelSerializer` behavior. This involves a little more code, but ensures
255 that the resulting behavior is more transparent.
256
257 ---
258
259 ## Writing custom validators
260
261 You can use any of Django's existing validators, or write your own custom validators.
262
263 ### Function based
264
265 A validator may be any callable that raises a `serializers.ValidationError` on failure.
266
267 def even_number(value):
268 if value % 2 != 0:
269 raise serializers.ValidationError('This field must be an even number.')
270
271 #### Field-level validation
272
273 You can specify custom field-level validation by adding `.validate_<field_name>` methods
274 to your `Serializer` subclass. This is documented in the
275 [Serializer docs](https://www.django-rest-framework.org/api-guide/serializers/#field-level-validation)
276
277 ### Class-based
278
279 To write a class-based validator, use the `__call__` method. Class-based validators are useful as they allow you to parameterize and reuse behavior.
280
281 class MultipleOf:
282 def __init__(self, base):
283 self.base = base
284
285 def __call__(self, value):
286 if value % self.base != 0:
287 message = 'This field must be a multiple of %d.' % self.base
288 raise serializers.ValidationError(message)
289
290 #### Accessing the context
291
292 In some advanced cases you might want a validator to be passed the serializer
293 field it is being used with as additional context. You can do so by setting
294 a `requires_context = True` attribute on the validator class. The `__call__` method
295 will then be called with the `serializer_field`
296 or `serializer` as an additional argument.
297
298 class MultipleOf:
299 requires_context = True
300
301 def __call__(self, value, serializer_field):
302 ...
303
304 [cite]: https://docs.djangoproject.com/en/stable/ref/validators/