Issue
When I test my endpoints using Postman I get the message Method \"POST\" not allowed
when I try to create a new truck using my createTruck function. I am able to delete, update, and get trucks from my database. Also I am able to create a new truck in Django Admin.
views.py
@api_view(['POST'])
def createTruck(request):
data = request.data
user = request.user
truck = Truck.objects.create(
user=user,
image=data['image'],
make=data['make'],
prototype=data['prototyp'],
year=data['year'],
serviceInterval=data['serviceInterval'],
nextService=data['nextService'],
seats=data['seats'],
bedLength=data['bedLength'],
color=data['color'],
vin=data['vin'],
currentMileage=data['currentMileage']
)
print("request", request)
serializer = TruckSerializer(truck, many=False)
return Response(serializer.data)
@api_view(['DELETE'])
def deleteTruck(request, pk):
truck = Truck.objects.get(id=pk)
truck.delete()
return Response('Truck Deleted!')
urls.py
urlpatterns = [
path('trucks/', views.getTrucks, name="trucks"),
path('trucks/<str:pk>/', views.getTruck, name="truck"),
path('trucks/create/', views.createTruck, name="create-truck"),
path('trucks/delete/<str:pk>/', views.deleteTruck, name="delete-truck"),
path('trucks/update/<str:pk>/', views.updateTruck, name="update-truck"),
]
I might be passing in user wrong, but I'm not sure.
The Postman URL is
http://127.0.0.1:8000/api/trucks/create/
The body is
{
"user": 1,
"image": "/images/2016-tundra-600x400.jpeg",
"make": "Toyota",
"prototype": "Tundra",
"year": 2016,
"serviceInterval": 720,
"nextService": 600,
"seats": 2,
"bedLength": "5.50",
"color": "blak",
"vin": "0989098ad2321",
"currentMileage": 20000
}
Solution
Just change your URL pattern. It is a URL pattern conflict, that create-truck-pattern tries to get the truck with pk:create
. The standard solution is to change the type of pk from str to int. But the other solution is to change URL priority in your patterns and move create-truck on step upper.
Recommended solution:
urlpatterns = [
path('trucks/', views.getTrucks, name="trucks"),
path('trucks/<int:pk>/', views.getTruck, name="truck"),
path('trucks/create/', views.createTruck, name="create-truck"),
path('trucks/delete/<str:pk>/', views.deleteTruck, name="delete-truck"),
path('trucks/update/<str:pk>/', views.updateTruck, name="update-truck"),
]
other solution:
urlpatterns = [
path('trucks/', views.getTrucks, name="trucks"),
path('trucks/create/', views.createTruck, name="create-truck"),
path('trucks/<str:pk>/', views.getTruck, name="truck"),
path('trucks/delete/<str:pk>/', views.deleteTruck, name="delete-truck"),
path('trucks/update/<str:pk>/', views.updateTruck, name="update-truck"),
]
Answered By - mrash
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.