简体   繁体   中英

“CSRF Failed: CSRF token missing or incorrect.” in Django Rest: UpdateModelMixin

I am using UpdateModelMixin from Django rest framework to update the entries from the Test model.

from django.utils.decorators import method_decorator
from django.views.decorators.cache import never_cache
from rest_framework import mixins, filters, viewsets
decorators = [never_cache]

@method_decorator(decorators, name='dispatch')
class TestViewSet(mixins.ListModelMixin,
                     mixins.RetrieveModelMixin,
                     mixins.UpdateModelMixin,
                     viewsets.GenericViewSet):

    queryset = Test.objects.all()
    serializer_class = TestSerializer
    filter_backends = [filters.DjangoFilterBackend]
    filter_class = TestFilter

When I try to update the object from the Test Model It's giving following error -

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

Can anyone please help me to resolve this issue?

This is an old question, but it deserves an answer, since people might come to this page looking for one.

If there is a csrf token problem, it means that the page you are using is not passing the csrf token. Since you don't say how you are accessing the data, I am going to assume it is JavaScript, since that is most likely, so I'll give you an example of how to fix it there, but the process is simply to get the csrf token from the existing cookie, then pass it along as a cookie to the API.

Here is an example AJAX call from JavaScript that passes a csrf token:

var data={ foo: "bar" };
$.ajax({
    url: '/api/schedule/',
    type: "PATCH",
    data: JSON.stringify(data),
    beforeSend: function(xhr) {
        xhr.setRequestHeader('X-CSRFToken', Cookies.get('csrftoken'))
    },
    contentType: "application/json",
});

EDIT: This uses the JavaScript cookie library.

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