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")
validated_data is an OrderedDict and you can see it only after is_valid() and is_valid() == True.
Custom exception handlingThe exception handler function should either return a Response object, or return None if the exception cannot be handled. If the handler returns None then the exception will be re-raised and Django will return a standard HTTP 500 'server error' response.
A validator is a callable that takes a value and raises a ValidationError if it doesn't meet some criteria. Validators can be useful for reusing validation logic between different types of fields.
REST is a loosely defined protocol for listing, creating, changing, and deleting data on your server over HTTP. The Django REST framework (DRF) is a toolkit built on top of the Django web framework that reduces the amount of code you need to write to create REST interfaces.
The solution I found was to override the destroy method on the api.
class CallDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = XCall.objects.all()
serializer_class = CallSerializer
...
def destroy(self, request, *args, **kwargs):
obj = self.get_object()
if obj.survey:
return Response(data={'message': "Too late to delete"},
status=status.HTTP_400_BAD_REQUEST)
self.perform_destroy(obj)
return Response(status=status.HTTP_204_NO_CONTENT)
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 ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With