Search code examples
djangodjango-rest-frameworkdjango-csrf

"rest_framework CSRF token failed" but it's already set in the request header as "X-CSRF-Token"


Already checked other topics and tried the answered solutions but the problem stays still. My put/post requests are return with an error.

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

Although I am sending CSRFToken inside the header axios.defaults.headers.common['X-CSRF-Token'] = CSRF_TOKEN;

And there it is the CSRF

enter image description here

By the way, in settings.py I set the authentication classes

'DEFAULT_AUTHENTICATION_CLASSES': [
    'rest_framework.authentication.TokenAuthentication',
    'rest_framework.authentication.SessionAuthentication',

],

Additionally views.py

class ProjectViewSet(viewsets.ViewSet):

  permission_classes = [IsAuthenticated | IsSuperUser]

  # retrieve works without a problem
  def retrieve(self, request, pk=None):
    queryset = Project.objects.all().filter(company_user=self.request.user)
    project = get_object_or_404(queryset, pk=pk)
    serializer = ProjectSerializer(project)
    return Response(serializer.data)

  def update(self, request, pk=None):
    # CSRF request problem
    pass

  def partial_update(self, request, pk=None):
    # CSRF request problem
    pass

and urls.py

router = DefaultRouter()
router.register('project', views.ProjectViewSet, basename='project')

urlpatterns = router.urls

Do I missing something here? Why do I keep having the CSRF error?


Solution

  • You should use X-CSRFToken instead of X-CSRF-Token