简体   繁体   中英

Getting 403 (Forbidden) React + Django

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}`)
    }

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!')

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM