Reputation: 693
Would appreciate if someone can help me find the problem. I know there are a lot of solutions regarding this specific problem. Have been stuck here for a quite a long time now.
My code
Views
class HolidayList(ListCreateAPIView):
queryset = Holiday.objects.all()
serializer_class = HolidaySerializer
permission_classes = [IsAdminUser, IsAuthenticated]
authentication_classes = [SessionAuthentication,BasicAuthentication]
url
url(r'^$', HolidayList.as_view(), name='holiday-list-api'),
Getting this error
{"detail":"CSRF Failed: CSRF token missing or incorrect."}
my rest framework configuration
REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
'base.csrf_exempt.CsrfExemptSessionAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
'rest_framework.permissions.IsAdminUser',
),
}
Tried to use CsrfExempt but no luck. What am i missing here ?
from rest_framework.authentication import SessionAuthentication
class CsrfExemptSessionAuthentication(SessionAuthentication):
def enforce_csrf(self, request):
return
Upvotes: 0
Views: 576
Reputation: 743
Had the same problem and solved with the following jquery snippet
<script>
$(document).ready(function(){
$.ajaxSetup({headers: {"X-CSRFToken": getCookie("csrftoken")}});
});
function getCookie(name) {
function escape(s) { return s.replace(/([.*+?\^${}()|\[\]\/\\])/g, '\\$1'); };
var match = document.cookie.match(RegExp('(?:^|;\\s*)' + escape(name) + '=([^;]*)'));
return match ? match[1] : null;
}
</script>
csrf_token is stored in the cookie called "csrftoken" and you need to pass it to the request header. In your case to your POST request header.
hope it will help.
Upvotes: 1