Amr
Amr

Reputation: 2235

Django REST Framework with ForeignKey on_delete=models.PROTECT

when I try to delete Django model object that is ForeignKey in another model with option on_delete=models.PROTECT, the error returned is the normal Django 500 Exception HTML web page, how to make Django rest frame work return json response with the error, is there a way for DRF to do that by default or it should be customized?

Upvotes: 1

Views: 896

Answers (3)

pierreben
pierreben

Reputation: 396

To complete MSI Shafik answer, specifically for django-rest-framework, you can override the destroy method to catch the exception and return protected objects in a response to handle an error message in your application.

For example:

from django.db.models.deletion import ProtectedError

    def destroy(self, request, *args, **kwargs):
        try:
            return super().destroy(request, *args, **kwargs)
        except ProtectedError as protected_error:
            protected_elements = [
                {"id": protected_object.pk, "label": str(protected_object)}
                for protected_object in protected_error.protected_objects
            ]
            response_data = {"protected_elements": protected_elements}
            return Response(data=response_data, status=status.HTTP_400_BAD_REQUEST)

Upvotes: 0

MSI Shafik
MSI Shafik

Reputation: 139

You can catch the error by using ProtectedError expceptions. Like this-

from django.db.models import ProtectedError

try:
    # Write here your code
except ProtectedError:
    # Return your customer validation error

Upvotes: 0

Antonio Mande
Antonio Mande

Reputation: 101

Raising 500 Exception is the expected behavior. You have to customize to have a custom error. You can refer to this similar question

Upvotes: 1

Related Questions