Home > Mobile >  django post request: Forbidden (CSRF token missing.): /categories
django post request: Forbidden (CSRF token missing.): /categories

Time:06-22

In my file view.py I want to write a class based on View with get and post methods for API. Get is already written, it works. There was a problem with the post:

Code of this class:

class CategoryListView(View):

    def get(self, request):
        if not check_correct_api_secret(request):
            return HttpResponseForbidden('Unknown API key')

        query_set = Category.objects.all()
        query_params = request.GET
        query_set = paginate(query_params, query_set)
        items_data = serialize_category_list(request, query_set)
        return JsonResponse(items_data, safe=False)

    # Method code is written for example, just to see some kind of reaction to the post request
    def post(self, request):
        query_params = request.POST
        name = query_params.get('name')
        Category.objects.create(name=name)

        return HttpResponse(201)

I try send post request: /categories?name=Category6 (For example) And I get error: Forbidden (CSRF token missing.): /categories [21/Jun/2022 16:21:26] "POST /categories?name=Category777 HTTP/1.1" 403 2506

My urls.py:

urlpatterns = [
    path('admin/', admin.site.urls),
    path('categories', CategoryListView.as_view()),
]

CodePudding user response:

Try to add @csrf_protect in your post method.

@csrf_protect
    def post(self, request):
            query_params = request.POST
            name = query_params.get('name')
            Category.objects.create(name=name)
    
            return HttpResponse(201)

Or just to test it add @csrf_exempt

CodePudding user response:

This error can occur if you are not using CsrfViewMiddleware. In this case you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data.

  • Related