Search code examples
pythondjangodjango-rest-frameworkdjango-rest-viewsetsdjango-rest-framework-jwt

Can't submit a post request using Django rest framework ("detail": "CSRF Failed: CSRF token missing or incorrect.")


I am into a weird situation I am login into site and try to submit form if I use permission_classes = [AllowAny] or isAuthenticate classes I get error CSRF Failed: CSRF token missing or incorrect

And in following scenario it gives a popup to enter password and user name . My full class is like

class AddReview(APIView):
    serializer_class = ReviewSerializer
    authentication_classes = (BasicAuthentication,)
    def post(self, request):  
        rest = request.POST.get('restaurant')
        dish = request.POST.get('dish')

And my settings.py is

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',

    ),
}

I just want to submit a post custom form to submit data. Any help or suggestion to make question good would be highly appericiated.

Update

I am able to submit form by using this

class SessionAuthentication(SessionAuthentication):
    def enforce_csrf(self, request):
        return

But why I have to enforce it ? What I am doing wrong ?


Solution

  • Ideally, you website form should have a csrf token and that should also be sent to server. Maybe something like :

    <form method="post">{% csrf_token %}</form>
    
    1. The CSRF middleware is activated by default in the MIDDLEWARE setting.
    2. If you want to disable CSRF protection just a few views use csrf_exempt() decorator

    References

    https://docs.djangoproject.com/en/2.2/ref/csrf/#csrf-protection-should-be-disabled-for-just-a-few-views

    https://docs.djangoproject.com/en/2.2/ref/csrf/