I am trying to use the $post request from javascript into my django template, but there is something I am missing, since it is not working.
I will show you my code:
This is the template:
//TEMPLATE
//This code will send a string to django "views.py" file,
//then it will show a pop up message from the data retreived from "views.py"
function test_post(){
$.post("/xhr_test",
{name: "Monty", food: "Spam", csrftoken : "{{ csrf_token }}" },
function(data) {
alert(data)
;});
};
This is the views.py:
// VIEWS.PY
//Depending on the type of request it will send a message or another.
def xhr_test(request):
if request.is_ajax():
if request.method == 'GET':
message = "This is an XHR GET request"
elif request.method == 'POST':
message = "This is an XHR POST request"
# Here we can access the POST data
print request.POST
else:
message = "No XHR"
return HttpResponse(message)
This code does not show the “This is an XHR POST request” message as it should. However it does show the “This is an XHR GET request” message when using the $get request.
A similar doubt was answer in this thread. Even though I am using the answers that were provided there, the code does not work.
I am guessing the answer must be related to the “{{ csrf_token }}”, but not sure how…
Any type of help will be appreciated.
If this is due to csrf token (you can check it in your browser using firebug), then use this in your views.py