Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

268
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!