Reputation: 55
when I try to delete or edit a task(todo), I get DELETE http://127.0.0.1:8000/api/tasks/4/ 403 (Forbidden)
. But, when I want just to get tasks, everything works. Maybe the problem in CORS. I have 'corsheaders' in INSTALLED_APPS and 'corsheaders.middleware.CorsMiddleware' in MIDDLEWARE
serializers.py
class TaskSerializer(serializers.ModelSerializer):
class Meta:
model = Task
fields = ('pk', 'title', 'created_at', 'is_done')
settings.py
CORS_ALLOW_METHODS = [
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
]
CORS_ALLOWED_ORIGINS = [
"http://localhost:3000",
"http://127.0.0.1:8000",
]
App.js
function removeTodo(id){
axios.delete(`http://127.0.0.1:8000/api/tasks/${id}`)
}
Upvotes: 1
Views: 1385
Reputation: 11
In your settings.py just add:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
)
}
This works because with these settings we get to use Django's standard django.contrib.auth
permissions or allow read-only access for unauthenticated users.
Upvotes: 1
Reputation: 55
In views.py I didn't make a @api_view(['DELETE']) etc. And add it to urls.py views.py
@api_view(['GET'])
def taskList(request):
tasks = Task.objects.all().order_by('-id')
serializer = TaskSerializer(tasks, many=True)
return Response(serializer.data)
@api_view(['POST'])
def taskCreate(request):
serializer = TaskSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
@api_view(['DELETE'])
def taskDelete(request, pk):
task = Task.objects.get(id=pk)
task.delete()
return Response('Item successfully delete!')
Upvotes: 1