So i am creating a simple API sing Django. So every time i am getting the APPEND_SLASH issue while making a POST request on localhost:8000/cars from PM , in the body I am passing a JSON request body with one field based on the value of which the data is gonna be filtered from the sqlite DB.
Also , i am unable to find “APPEND_SLASH” in my settings.py!!
Below is the error message:
RuntimeError: You called this URL via POST, but the URL doesn’t end in a slash and you have APPEND_SLASH set. Django can’t redirect to the slash URL while maintaining POST data. Change your form to point to localhost:8000/cars/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings.
My urls.py:
from django.urls import path,include
from . import views
urlpatterns=[
path('cars/',views.cars,name='cars'),
]
My views.py:
from django.shortcuts import render
from django.http import HttpResponse
from cars.models import car
import json
from django.core import serializers
from django.http import JsonResponse
def cars(request):
if request.method=="GET":
all_cars=car.objects.all()
cars_data=[]
for each_car in all_cars:
cars_data.append({
'name': each_car.name,
'color': each_car.color,
'fuel': each_car.fuel
})
return JsonResponse(cars_data,safe=False)
elif request.method == 'POST':
data=json.loads(request.body)
color_of_car=data.get('color_of_car')
if color_of_car is not None:
one_car=car.objects.filter(color=color_of_car)
output=[]
for each_car in one_car:
output.append({
'name': each_car.name,
'color': each_car.color,
'fuel': each_car.fuel
})
return JsonResponse(output,safe=False)
The request body i am passing in body through Postman (PM)
{ "color_of_car":"black" }
PS; Also , please suggest what else can i change if i am starting a new project from scratch in order to not face this error again?
sundaram saroj is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.