Encountering 500 Internal Server Error on Django API POST request
I am encountering a 500 Internal Server Error when trying to send a POST request to a Django API to create an object. I have checked my code but cannot identify the source of the issue.
Here’s the code I’m using: Serializer
class DeliverableSerializer(serializers.ModelSerializer):
class Meta:
model = Deliverable
fields = ("num", "project", "reviewer", "deliverable_type", "description", "due_date",
"id", "draft")
Views
class DeliverableAPIView(APIView):
def post(self, request, format=None):
serializer = DeliverableSerializer(data=request.data)
if serializer.is_valid():
instance = serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def put(self, request, pk, format=None):
try:
deliverable = Deliverable.objects.get(pk=pk)
serializer = DeliverableSerializer(deliverable, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
except Exception as e:
return Response({"error": "An unexpected error occurred."}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
URLs
path('api/deliverables/', DeliverableAPIView.as_view(), name='deliverable-list'), # For POST
path('api/deliverables/<int:pk>/', DeliverableAPIView.as_view(), name='deliverable-detail'), # For PUT
POST Request in My Script
def post_data(endpoint, data):
"""Send data to the API via POST request."""
try:
response = requests.post(API_URL + endpoint, json=data, timeout=10)
response.raise_for_status() # Raises an HTTPError for bad responses
return response.json() # Return the JSON response if needed
except requests.exceptions.HTTPError as err:
raise Exception(f"HTTP error occurred while posting to {endpoint}: {err}") # For HTTP errors
except requests.exceptions.RequestException as err:
raise Exception(f"Error posting data to {endpoint}: {err}")
When I try to send a POST request to the endpoint /api/deliverables/, it generates a 500 error. I also tried using Postman but I cannot test it properly due to restrictions on localhost.
I’ve checked that my request data matches the serializer fields, and the model is set up correctly. What could be the reasons for this 500 error, and how can I diagnose it?
Thank you in advance for your help.
I tried sending a POST request to my Django API at the endpoint /api/deliverables/
using a script and Postman. I expected the API to accept the data according to my DeliverableSerializer
and create a new Deliverable object in the database. However, instead of successfully creating the object, I received a 500 Internal Server Error, indicating something went wrong on the server side.
Here's the structure of the data I'm sending in the request:
{
"num": 1,
"project": 1, # ID of the project
"reviewer": 2, # ID of the reviewer
"deliverable_type": 3, # ID of the deliverable type
"description": "This is a test deliverable.",
"due_date": pd.to_datetime(row['Due Date'], errors='coerce').date().strftime('%Y-%m-%d')
"id": "folder_id_123",
"draft": true # Boolean value
}
I also checked the request data and ensured it matched the expected fields in the serializer, but the error persists.