Over the last week or so I have been struggling to successfully implement a jQuery ajax request to pass data from a javascript function within my annualgoals.html to a django view in order to save data to my database. Currently I am just trying to test the data transfer by printing the data on the django end.
I have already checked out the following threads but cannot see any that show the same error as I can see (I am almost certainly missing something obvious).
Forbidden (CSRF token missing or incorrect) Django error
"CSRF token missing or incorrect" while post parameter via AJAX in Django
While a missing CSRF token was my first problem, the answers on StackOverflow and the django docs do a good job of explaining what must be done to ensure the csrf token is included. However, when following the recommended steps I receive the following django error:
response.set_cookie(settings.CSRF_COOKIE_NAME, AttributeError: 'NoneType' object has no attribute 'set_cookie'
My code is as follows:
annualgoals.html
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
var data = [1, 2, 3, 4]
var csrftoken = getCookie('csrftoken');
// Ajax Setup
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
// Ajax Call
$.ajax({
type: 'POST',
url: "{% url 'LifeAdmin:saveAnnualGoals' %}",
data: {'data[]': data},
});
views.py
@ensure_csrf_cookie
@login_required
def saveAnnualGoals(request):
if request.method == 'POST':
data = request.POST.get('data')
print(data)
urls.py
url(r'^saveAnnualGoals$', views.saveAnnualGoals, name='saveAnnualGoals')
I am using Django 1.10.5 and Python 3.6.1
Any help would be greatly appreciated!!
Thanks :)