I want to run a validation before an object is deleted, to prevent deletion in certain cases and return as a validation error. How do I do that? What I have currently doesn't seem right:
class CallDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = XCall.objects.all()
serializer_class = CallSerializer
...
def pre_delete(self, obj):
if obj.survey:
raise serializers.ValidationError("Too late to delete")
You can solve it with permissions:
Then add to your view's permission_classes
Rather than raising a
ValidationError
, I will just raise a ParseError or another custom error that fits the error description:The solution I found was to override the destroy method on the api.
For me makes much more sense to validate on the destroy method instead of validating on the object permission check as avances123 mentioned, since permission should only check for permission stuffs, and doesn't return any messages related to validation.
Hope that helps ;)
Update
Hmmm. Right yes. In that case I'd raise the exception in
pre_delete
just as you are and overridedelete
to wrap thedestroy
call in atry
block.If you
except ValidationError as e
you can use that to construct the response you want by hand...... or such.
You could probably populate
self._errors
and leverage the existing error response behaviour but I can't think how to do that off-hand.I hope that helps.
First Answer (didn't work):
Check the doc on Object Level Validation.
Implement
validate
to check if the survey is set:If
attrs
isn't what you need here you'll have to do something cleverer — but it will get your error in at the validation stage.I hope that helps.