Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

272
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda