I am starting using Django REST framework, I found the framework doesn't have the same level of form validation. If I use form validation, I have the endpoint as the form, and serializes the data, which seems it is not a benefit to use the framework. How can I solve this?
-
I'm not sure I understand the question here. Is it that you can't get the same degree of validation as you would in a normal form, or that your validation isn't working? The DRF validation docs are pretty comprehensive ...jvc26– jvc262015-05-26 18:16:11 +00:00Commented May 26, 2015 at 18:16
-
Actually I am here with, I believe, the same question. The DRF docs which @jvc26 linked seems to mostly cover field validation. I too would like to know how to do the equivalent of form-level validation, as Django itself is able to do. For example, I am trying to add validation to ensure that a start date is prior to an end date. I can't find an example anywhere.trpt4him– trpt4him2015-05-27 02:08:23 +00:00Commented May 27, 2015 at 2:08
-
jvc26, Yes, the DRF has a reasonable level of validation, but moving from the form validation, it lacks some features, such as form fields rendering, which is announced to be adapted as I have gathered, but don't know when.user2307087– user23070872015-05-29 01:38:58 +00:00Commented May 29, 2015 at 1:38
Add a comment
|
1 Answer
Assuming what you are referring to is object level validation. (I.e. acting on more than one field together) you need to do this in the serializer (as per serializer docs) this is done by overriding:
def validate(self, data):
On the serializer class.
An example of this (from the included link):
def validate(self, data):
"""
Check that the start is before the stop.
"""
if data['start'] > data['finish']:
raise serializers.ValidationError("finish must occur after start")
return data
1 Comment
trpt4him
This worked for me -- this is exactly what I was trying to find in the docs, thanks! Would be great if that section were linked to from the Validators page in the docs.