Ritankar Bhattacharjee
Ritankar Bhattacharjee

Reputation: 756

How to change the status code that is recieved in the response in case of specific exceptions in Django rest framework

I am adding some details to my Django model from a react frontend. Everything is working fine and the API request is made with Axios. The data that is being submitted is an OneToOne Field with the user and hence submitting more than once raises an Integrity error of Unique Constraint. But the response I receive back has a status of 200. This triggers a notification in my frontend that says details submitted every time the button is pressed. However. that is not being submitted the second time because of the Integrity Error.

My question is if I handle the Integrity Error exception separately how can I send a different status rather than 200 as shown below

config: {transitional: {…}, transformRequest: Array(1), transformResponse: Array(1), timeout: 0, adapter: ƒ, …}
data: {message: 'UNIQUE constraint failed: teacher_teacherdetail.user_id'}
headers: {content-length: '39', content-type: 'application/json'}
request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
status: 200
statusText: "OK"

Currently I am handling the exception as below

try:
 # some code
    
    except IntegrityError as e:
      
      message = {
       "error": str(e)
      }
      
      return Response(message)
    
    
    except Exception as e:
      
      message = {
        "message": "exception",
        "error": str(e)
      }
      
      return Response(message)

Upvotes: 2

Views: 3145

Answers (1)

Felix Eklöf
Felix Eklöf

Reputation: 3730

You need to specify the error. Here you can find all valid variables

from rest_framework import status

message = {
    "error": str(e)
}
      
return Response(message, status=status.HTTP_400_BAD_REQUEST)

Upvotes: 3

Related Questions