Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

169
Visualizações
Fetch API post data not receiving in Django view

What I am trying to do ?

I am trying to send a post request with data to a Django view using fetch API like this:

javascript:

const data = {
  search_text: "",
  months: 6,
  property_type: "all"
};
const headers = {
   'Accept': 'application/json',
   'Content-Type':'application/json',
   'X-Requested-With':'XMLHttpRequest'
}

fetch("some-url", {method: "POST", headers: headers, body: JSON.stringify(data)})
  .then((response) => response.json())
  .then((data) => console.log(data));

views.py:

class MyView(View):

  def post(self, request, *args, **kwargs):
     print("request: ", request.POST)
     # do stuff with post data

urls.py:

re_path(r"^my_view/$", login_required(csrf_exempt(MyView.as_view())), name="my_view"),

Problem

When I try to access the post data in my Django view I get empty QueryDict and the output of the terminal is this:

request:  <QueryDict: {}>
[06/Jan/2022 06:48:19] "POST /my_app/my_view/ HTTP/1.1" 200 114
Forbidden (CSRF token missing or incorrect.): /inbox/notifications/api/unread_list/
[06/Jan/2022 06:48:22] "{"search_text":"","months":"6","property_type":"all"}GET /inbox/notifications/api/unread_list/?max=5 HTTP/1.1" 403 12291

If you notice at the last line the post data seems to get added in the terminal why is that happening ? also why I get Forbidden (CSRF token missing or incorrect.) even when I am using csrf_exempt in the urls ?

I have tried looking it up and nothing seems to work. We are using react and I know axios can also be used but it should work with fetch API why isn't it working please help.

Edit:

Even after adding csrf token like mentioned in the docs and removing csrf_exempt from the urls I still get the same issue.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

This is because your view is protected by a CSRF-protection-middleware.

You have two possibilities:

  • Make the view exempt from this protection, see csrf_exempt
  • Add the CSRF token to your request (see answer from Yevgeniy Kosmak)
about 4 years ago · Juan Pablo Isaza Relatório

0

Okay fixed the issue it seems the data I was looking for was not in request.POST but instead in request.body did the following changes:

import json

class MyView(View):

  def post(self, request, *args, **kwargs):
     print("request: ", json.loads(request.body))
     # do stuff with post data

request.body returns byte string so need to convert that to json with json.loads for more info read docs

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda