CSRF with jquery and $ .post in django 1.3

In django 1.3 you now need to use csrf even with ajax. I am using jquery and now I want to add the csrf token to $ .post. How can i do this? I am not very good at jquery, so it would be nice with a good description.

This is a rating application, and a message is sent when you click on a star. I saw django docs but don't understand what to do in my situation. My code is below:

$(function() { $("#avg").children().not(":input").hide(); $("#rating-widget").children().not("select").hide(); $caption = $("<span/>"); $("#avg").stars({captionEl: $caption}); $("#rating-widget").stars({ inputType: "select", cancelShow: false, captionEl: $caption, callback: function(ui, type, value){ --------------> $.post($("#rating-widget").attr("action"), {score: value}, function(data){ }); } }); $caption.appendTo("#rating-widget"); }); 

I must say that javascript is not in the template, but in a static file. It would be better to place it in the template so that I can use {{ csrf_token }}

Thanks in advance!

+6
source share
3 answers

Put this code in front of your function. He will take care of the CSRF.

 $('html').ajaxSend(function(event, xhr, settings) { 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; } if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) { // Only send the token to relative URLs ie locally. xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); } }); 
+7
source

In the django documentation you can find a simple description of how to automatically include the csrf token in every ajax request!

+3
source

You do not need to use a form! Just create a new URL bound to the function that the "asterisks" send. for instance

 (r'^myapp/star-post/(?P<post_id>.*)/$','myapp.views.myview') 

Therefore, if you send a request to this URL, it will find the message in your database, changing the field to โ€œfavoritesโ€ and return the response to ajax.

Then you can have a callback function on successful execution that changes CSS accordingly (fill the star, etc.). This way you do not need to worry about CSRF.

But you may ask, what about attacks on cross-site scripts! Well, if you use user authentication with cookie verification, you donโ€™t have to worry about that! Aaaand, you are good to go.

+1
source

Source: https://habr.com/ru/post/889496/


All Articles