I am a newbie to Django and its REST Framework, I am trying to design an API that allows me to perform the basic operations of the CRUD, both the GET, POSt and PUT methods work correctly, however when I try to implement the DELETE method I get a very particular error:
This is my main urls.py file:
from django.conf.urls import url
from django.urls import path
from rest_framework_simplejwt.views import (
TokenObtainPairView, TokenRefreshView)
from pethomeApp import views
urlpatterns = [
path('login/', TokenObtainPairView.as_view()),
path('refresh/', TokenRefreshView.as_view()),
path('user/', views.UserCreateView.as_view()),
path('pet/', views.petView.petAPI),
path('pet/<int:pk>/', views.petView.petAPI),
]
This is my petViwe.py file:
from rest_framework import status, views
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
from django.http.response import JsonResponse
from pethomeApp.models import Pet
from pethomeApp.serializers import PetSerializer
# Create your views here.
@csrf_exempt
def petAPI(request, id=0):
if request.method == 'GET':
if id == 0:
pets = Pet.objects.all()
serializer = PetSerializer(pets, many=True)
return JsonResponse(serializer.data, safe=False)
else:
pet = Pet.objects.get(id=id)
serializer = PetSerializer(pet)
return JsonResponse(serializer.data, safe=False)
elif request.method == 'POST':
data = JSONParser().parse(request)
serializer = PetSerializer(data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse("Added successfuly", safe=False)
return JsonResponse("Failed to add", safe=False)
elif request.method == 'PUT':
data = JSONParser().parse(request)
pet = Pet.objects.get(id_pet=data['id_pet'])
serializer = PetSerializer(pet, data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse("Update successfuly", safe=False)
return JsonResponse("Failed to update")
elif request.method == 'DELETE':
pet = Pet.objects.get(id_pet=id)
pet.delete()
return JsonResponse("Deleted successfuly", safe=False)
And I am trying to test the delete method like this:
Excuse my ignorance, does anyone have any idea why it takes the DELETE method as GET and does not allow me to delete a record from the database?
CodePudding user response:
The name of the URL parameter is pk
, not id
. Indeed, if we look at the path pattern, we see:
urlpatterns = [
path('pet/<int:pk>/', views.petView.petAPI),
]
You thus should change the signature to:
@csrf_exempt
def petAPI(request, pk=0):
# …
and use pk
instead of id
in the function.
CodePudding user response:
change the value in url.py
path('pet/<int:id>/', views.petView.petAPI),
from pk
to id