Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django REST Framework: Validate before a delete

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")
like image 351
Neil Avatar asked Jan 27 '14 13:01

Neil


People also ask

What is validated data in Django REST framework?

validated_data is an OrderedDict and you can see it only after is_valid() and is_valid() == True.

How do I create a custom exception in Django REST framework?

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.

What is Django validator?

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.

How does Django rest work?

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.


1 Answers

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 ;)

like image 160
Pablo Abdelhay Avatar answered Sep 21 '22 13:09

Pablo Abdelhay