Reputation: 1042
I have written logic to delete an item in the apiview of Django. The logic is to assign that item to a variable and by using Try and Except. It works fine when there is an object but when there is no object I got an error saying "leads.models.Lead.DoesNotExist: Lead matching query does not exist."
I should be getting a message of Deal doesn't exist with 400 status as I had that inside Except. I am getting 500 errors in the post.
def delete(self, request,pk, *args, **kwargs):
id = pk
lead = Lead.objects.get(id=id)
# abc.delete()
# return Response({"message": "Lead has been deleted"},
# status=status.HTTP_200_OK)
try:
lead = Lead.objects.get(id=id)
if lead.delete():
return Response({
"message": "Deals has been deleted"
},status=status.HTTP_204_NO_CONTENT)
except lead.DoesNotExist:
return Response({
"message": "Deal doesnt exist"
},status=status.HTTP_400_BAD_REQUEST)
My urls is:
path('lead/<int:pk>', ChunksLeadCreate.as_view()),
I hope this code is enough to fix the issue.
Upvotes: 0
Views: 880
Reputation: 1042
I commented out the assignment of lead before Lead.Doesnot exist and it worked.
def delete(self, request,pk, *args, **kwargs):
id = pk
# lead = Lead.objects.get(id=id)
# abc.delete()
# return Response({"message": "Lead has been deleted"},
# status=status.HTTP_200_OK)
try:
lead = Lead.objects.get(id=id)
if lead.delete():
return Response({
"message": "Deals has been deleted"
},status=status.HTTP_204_NO_CONTENT)
except Lead.DoesNotExist:
return Response({
"message": "Deal doesnt exist"
},status=status.HTTP_400_BAD_REQUEST)
Upvotes: 1