29๐
โ
See below for how I changed your code. The csrf_token is assigned to a variable with Django templating. You can produce this variable in any of your Javascript code.
The token is then included in the header
<script>
var token = '{{csrf_token}}';
$("#id_username").change(function () {
console.log($(this).val());
var form = $(this).closest("form");
$.ajax({
headers: { "X-CSRFToken": token },
url: form.attr("data-validate-username-url"),
data: form.serialize(),
dataType: 'json',
success: function (data) {
if (data.is_taken) {
alert(data.error_message);
}
}
});
});
</script>
๐คceds
7๐
The documentation very well explained how to use AJAX
https://docs.djangoproject.com/en/2.1/ref/csrf/
- Get this library https://github.com/js-cookie/js-cookie/
- Add this
var csrftoken = Cookies.get('csrftoken');
-
The last step is configure ajax setup
function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } });
- Conditionally Require Only One Field In Django Model Form
- Git push heroku master: Heroku push rejected, no Cedar-supported app detected
0๐
Update to the steps above โ as the Django
documentation indicates you can use the Javascript Cookie library to do a Cookies.get('csrftoken')
. Also, I had to add {% csrf_token %}
before the function call. Might be obvious, but I didnโt know so providing it here to help others
- Best practice for handling HTTP HEAD request with Django on App Engine
- Django Model " has more than one ForeignKey to "
Source:stackexchange.com