I have the following code:
views.py
@api_view(['DELETE'])
@authentication_classes([TokenAuthentication])
@permission_classes([IsAuthenticated])
def selected_job_delete(request,pk=None):
if pk != None:
job=Job.objects.get(pk=pk)
jobdetail = Job_detail.objects.get(job=pk)
jobtrack = Job_track.objects.get(job = pk)
jr = Job_removed()
jdr = Job_detail_removed()
jtr = Job_track_removed()
jr.jobname = job.jobname
jr.owner = job.owner
jr.enabled = job.enabled
jr.start_date = job.start_date
jr.start_time = job.start_time
jr.date_added = job.date_added
jr.version = job.version
jr.save()
jdr.job = jr
jdr.json = jobdetail.json
jdr.save()
jtr.job=jr
jtr.jobdetail= jdr
jtr.save()
operation = job.delete()
data = {}
if operation:
data["Success"] = "Successfully deleted"
else:
data["Failure"] = "Unsuccessful"
return Response(data)
urls.py
path('api/jobs/<int:pk>/delete', views.selected_job_delete),
Lets say my database in Job
have the only following id of 40
. I want to delete it so i key the url of api/jobs/40/delete
and the deletion will happen, followed by the task in the function. The output result in my postman will show it is successfully deleted
. But if I key the url of api/jobs/41/delete
, the id of 41
does not exist in my database, it does not run my else statement to show unsuccessful
.
Instead it shows me
How can I make it to show unsuccessful
instead of the whole chunk of the error that it does not exist?
CodePudding user response:
Maybe you can do this:
try:
job.delete()
except:
data["Failure"] = "Unsuccessful"
return Response(data)
update
try:
job=Job.objects.get(pk=pk)
except: Job.DoesNotExist:
data["Failure"] = "Unsuccessful"
return data
CodePudding user response:
You must catch the exception Job.DoesNotExist
:
@api_view(['DELETE'])
@authentication_classes([TokenAuthentication])
@permission_classes([IsAuthenticated])
def selected_job_delete(request, pk=None):
if pk != None:
try:
job=Job.objects.get(pk=pk)
jobdetail = Job_detail.objects.get(job=pk)
jobtrack = Job_track.objects.get(job = pk)
jr = Job_removed()
jdr = Job_detail_removed()
jtr = Job_track_removed()
jr.jobname = job.jobname
jr.owner = job.owner
jr.enabled = job.enabled
jr.start_date = job.start_date
jr.start_time = job.start_time
jr.date_added = job.date_added
jr.version = job.version
jr.save()
jdr.job = jr
jdr.json = jobdetail.json
jdr.save()
jtr.job=jr
jtr.jobdetail= jdr
jtr.save()
operation = job.delete()
if operation:
return Response({"Success": "Successfully deleted"})
except Job.DoesNotExist:
pass
return Response({"Failure": "Unsuccessful"})