Forums

CSRF Failed: CSRF token missing or incorrect django rest framework`

Hello,

I am using django rest framework,

When I used the GET request it works well, but when I use POST request it shows

HTTP 403 Forbidden 
Allow: POST, OPTIONS
Content-Type: application/json 
Vary: Accept

{
    "detail": "CSRF Failed: CSRF token missing or incorrect."
}

I dont understatnd, where the error is comming

Thanks

If you are using an authentication scheme in DRF that requires CSRF validation, you need to include a valid CSRF token in your request for http methods that can change state on the server (like POST requests). See https://www.django-rest-framework.org/topics/ajax-csrf-cors/#csrf-protection

Yes, I added this in settings.py

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
    # 'rest_framework.authentication.SessionAuthentication',
    'rest_framework.authentication.BasicAuthentication',
]
}

In views.py

@api_view(['POST'])
def apipost(request):
    serializer = cvserializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
    else:
        print('serializer.errors', serializer.errors)

    return Response(serializer.data)

Now, the csrf error is gone, but the serializer.is_valid() is not true,

I checked the serializer.errors() =>

{'classes': [ErrorDetail(string='This field is required.', code='required')], 'date_d': [ErrorDetail(string='This field is required.', code='required')]}

how to solve this , thanks

How does your post look like?

@fjl, my input post looks like this -

{
    "classes":"person",
    "date":"2021-09-03"
}

Could you add debugging log before serializer = cvserializer(data=request.data) to show how request.data looks like?