I have given {% csrf_token %} inside the form. Do I have to give another {% csrf_token %} inside the AJAX $.ajax({ .......... )} ?
<form method="post" data-validate-username-url="{% url 'validate_username' %}">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Sign up</button>
</form>
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<script>
$("#id_username").change(function () {
console.log($(this).val());
var form = $(this).closest("form");
$.ajax({
url: form.attr("data-validate-username-url"),
data: form.serialize(),
dataType: 'json',
success: function (data) {
if (data.is_taken) {
alert(data.error_message);
}
}
});
});
</script>
The documentation very well explained how to use AJAX https://docs.djangoproject.com/en/2.1/ref/csrf/
var csrftoken = Cookies.get('csrftoken');
The last step is configure ajax setup
Update to the steps above - as the
Django
documentation indicates you can use the Javascript Cookie library to do aCookies.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 othersSee 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