Django Rest Framework complains about CSRF

I developed a simple web service but couldn't use the post with the Django Rest Framework as it complains about CSRF:

"detail": "CSRF Failed: CSRF cookie not set."

Removing the api_view decorator stops the message from appearing, but then I will not be able to access request.data. I think api_view checks for CSRF, although I added the csrf_exempt decorator.

It's my opinion:

@permission_classes((IsAuthenticated, )) @csrf_exempt @api_view(['POST']) def get_stats(request): """ Returns the stats available. """ user = request.user if request.method == 'POST': serializer = StatsRequestSerializer(data=request.data) stats_request = serializer.data return JSONResponse(stats_request) #serializer = QuizSerializer(user.quizes.all(), many=True) #return JSONResponse(serializer.data) response = ActionResponse(status='error', error='Invalid request') serializer = ActionResponseSerializer(response) return JSONResponse(serializer.data, status=400) 

This is my model:

 class StatsRequest(models.Model): """ A model which describes a request for some stats for specific users. """ start_date = models.DateField() end_date = models.DateField() 

and this is my POST request:

 {"start_date" : "1992-01-15", "end_date" : "1992-01-15" } 

Any ideas?

Additional Information:

 AUTHENTICATION_BACKENDS = ( 'social.backends.facebook.FacebookOAuth2', 'social.backends.google.GoogleOAuth2', 'django.contrib.auth.backends.ModelBackend' ) 
+3
python django csrf
04 Sep '15 at 13:03
source share
3 answers
0
Sep 04 '15 at 15:03
source share

So, trying to figure it out for a couple of hours, I finally did it. Tracking the source code for DRF and Django made me believe that I needed to find a workaround for this, since the CSRF check is done explicitly, even if it is turned off, probably the CSRF check is done in the api_view decorator. So I just created my own decorator:

 from functools import wraps from django.utils.decorators import available_attrs, decorator_from_middleware def csrf_clear(view_func): """ Skips the CSRF checks by setting the 'csrf_processing_done' to true. """ def wrapped_view(*args, **kwargs): request = args[0] request.csrf_processing_done = True return view_func(*args, **kwargs) return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view) 

and my opinion with the new decorator:

 @csrf_clear @api_view(['POST']) @permission_classes((IsAuthenticated, )) def get_stats(request): """ Returns the stats available. """ user = request.user if request.method == 'POST': serializer = StatsRequestSerializer(data=request.data) if serializer.is_valid(): stats_request = serializer.data return JSONResponse(stats_request) #serializer = QuizSerializer(user.quizes.all(), many=True) #return JSONResponse(serializer.data) response = ActionResponse(status='error', error='Invalid request') serializer = ActionResponseSerializer(response) return JSONResponse(serializer.data, status=400) 
0
04 Sep '15 at 18:19
source share

urls.py

 from django.views.decorators.csrf import csrf_exempt urlpatterns = [ url(r'^snippets/$', views.SnippetList.as_view()), url(r'^snippets/(?P<pk>[0-9]+)/$', csrf_exempt(views.SnippetDetail.as_view())), 

]

views.py

 from django.views.decorators.csrf import csrf_exempt from rest_framework.views import APIView class SnippetList(APIView): @csrf_exempt @need_post_parameters([PARAM_MESSAGE_OBJ]) def post(self, request, *args, **kwargs): data = request.POST.get(PARAM_MESSAGE_OBJ) try: message_obj = json.loads(data) except Exception as e: return HttpResponseBadRequest(error_json("Could not parse JSON")) 

http://www.chenxm.cc/post/509.html

0
Dec 21 '17 at 8:31
source share



All Articles