Answer the question
In order to leave comments, you need to log in
Disable CSRF for a single POST request?
There is a certain API request that a third-party site makes a request with some parameters, and after that I need to redirect to a specific page of my site.
from rest_framework.generics import GenericAPIView
from serializers import AddSomethingSerializer
class AddingSomething(GenericAPIView):
permission_classes = (permissions.AllowAny, )
serializer_class = AddSomethingSerializer
queryset = None
def post(self, request, **kwargs):
# .. Some magic ..
return HttpResponseRedirect(redirect_to=reverse('something_added'))
"detail": "CSRF Failed: CSRF token missing or incorrect."
@method_decorator(csrf_exempt)
def post(self, request, **kwargs)
@method_decorator(csrf_exempt, name='dispatch')
class AddingSomething(GenericAPIView):
from django.views.decorators.csrf import csrf_exempt
from views import AddingSomething
urlpatterns = [
url('^add_something/$', csrf_exempt(AddingSomething.as_view()), name='api-add-something'),
...
Answer the question
In order to leave comments, you need to log in
Drf, when using SessionAuthentication, forces a check for a valid CSRF token for insecure request methods. csrf_exempt decorators will not work with SessionAuthentication.
The solution option, in principle, has already been thrown off to you with links to SO.
from rest_framework.authentication import SessionAuthentication
class CsrfExemptSessionAuthentication(SessionAuthentication):
def enforce_csrf(self, request):
return None
class AddingSomething(GenericAPIView):
permission_classes = (permissions.AllowAny, )
serializer_class = AddSomethingSerializer
authentication_classes = (CsrfExemptSessionAuthentication,)
queryset = None
def post(self, request, **kwargs):
# .. Some magic ..
return HttpResponseRedirect(redirect_to=reverse('something_added'))
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question