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

492
Visualizações
Why do I get a 'CSRF token missing or incorrect' error?

I am trying to return a value from a View function in Django. That function is being called from a JavsScript code using Ajax, but I get thrown an error which reads 'Forbidden (CSRF token missing or incorrect)'.

JavaScript/Ajax

The Error message

The HTML code looks something like this:

    <div align="center" class="input-line">
     <form class="input-form" method="post">{% csrf_token %}
        <input type = "text" id = "ans" class = "form-control" name = "address" placeholder="Type postcode..."><br><br>
        <button id = "homeBtn" class="btn btn-primary">Find info</button><br><br>
     </form>
</div>

The View Function is:

    def result(request):
        if(request == 'POST'):
           param = request.form['my data']
           this = runAreaReview(param) #This returns a string
           return HttpResponse(this)
about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

method 1

For making post requests with ajax, you need to set a header called HTTP_X_CSRFTOKEN and set it's value to a cookie which is stored in the browser by name csrftoken. Reference. so in your ajax call, you should do something like this.

var csrftoken = Cookies.get('csrftoken');
 $.ajax(
     ...
     headers:{"HTTP_X_CSRF_TOKEN":csrftoken}
 );

also note that if you are using some reverse proxy server with something like nginx, make sure to froward this header as well to the django application.

method 2

you can disable csrf verification for this specific view by using an annotation. Reference

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def result(request):
    ...

method 3

The method below is NOT RECOMMENDED for security reasons

You can alwaws turnoff the csrf middleware in settings to get rid of it if you are just building something for recreational purpose and not for production.

about 4 years ago · Santiago Trujillo Relatório

0

for any one come across this thread, the HEADER key should be X-CSRFToken as for Django 2.1, links goes here https://docs.djangoproject.com/en/2.1/ref/csrf/

about 4 years ago · Santiago Trujillo 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