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)'.
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)
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.
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/