forbidden (csrf cookie not set.) django rest framework
- Import necessary modules in your views.py:
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from rest_framework.response import Response
- Add the
@api_view
decorator to your view function to define it as an API view:
@api_view(['GET'])
@permission_classes([IsAuthenticated])
@csrf_exempt
def your_view_function(request):
# Your view logic here
return Response({'message': 'Success'})
Use the
@permission_classes([IsAuthenticated])
decorator to ensure that only authenticated users can access the view.Apply the
@csrf_exempt
decorator to exempt the view from CSRF protection:
@csrf_exempt
def your_view_function(request):
# Your view logic here
return Response({'message': 'Success'})
- If you're using class-based views, use the
@method_decorator
to apply@csrf_exempt
:
from django.utils.decorators import method_decorator
from django.views import View
@method_decorator(csrf_exempt, name='dispatch')
class YourViewClass(View):
def get(self, request):
# Your view logic here
return Response({'message': 'Success'})
Ensure that you've imported csrf_exempt
and method_decorator
from the correct modules.
- Make sure your frontend includes the CSRF token in requests. If using AJAX, include the CSRF token in the headers:
// Example using jQuery
$.ajax({
type: "GET",
url: "your-api-endpoint/",
headers: {
"X-CSRFToken": csrf_token_from_cookie, // Replace with the actual CSRF token
},
success: function (data) {
console.log(data);
},
error: function (error) {
console.log(error);
}
});
Replace "your-api-endpoint/"
with the actual URL of your API endpoint and obtain the CSRF token from the cookie.
- Ensure that the CSRF middleware is enabled in your Django settings:
MIDDLEWARE = [
# ...
'django.middleware.csrf.CsrfViewMiddleware',
# ...
]
Make sure it's listed in the MIDDLEWARE
setting and not commented out.
- Verify that your Django project is using the
django.contrib.sessions.middleware.SessionMiddleware
middleware.
MIDDLEWARE = [
# ...
'django.contrib.sessions.middleware.SessionMiddleware',
# ...
]
Make sure it's listed in the MIDDLEWARE
setting and not commented out.
- Confirm that the
django.contrib.auth.middleware.AuthenticationMiddleware
middleware is also enabled:
MIDDLEWARE = [
# ...
'django.contrib.auth.middleware.AuthenticationMiddleware',
# ...
]
Make sure it's listed in the MIDDLEWARE
setting and not commented out.