Django Csrf Token For Ajax January 18, 2024 Post a Comment I have given {% csrf_token %} inside the form. Do I have to give another {% csrf_token %} inside the AJAX $.ajax({ .......... )} ? Solution 1: 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>CopySolution 2: The documentation very well explained how to use AJAX https://docs.djangoproject.com/en/2.1/ref/csrf/Baca JugaHow Do You Load A Custom Field In DjangoValueerror: Set_wakeup_fd Only Works In Main Thread On Windows On Python 3.8 With Django 3.0.2 Or Flask 2.0.0Django Model Unique Together Both WaysGet this library https://github.com/js-cookie/js-cookie/Add this var csrftoken = Cookies.get('csrftoken');The last step is configure ajax setupfunctioncsrfSafeMethod(method) { // these HTTP methods do not require CSRF protectionreturn (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); CopySolution 3: 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 Share You may like these postsSave Date In Django In Desired FormatHow To Read Image From Database(sqlite Django) Not Local File?How Do I Extend The Django Group Model?How Do I Refresh The Values On An Object In Django? Post a Comment for "Django Csrf Token For Ajax"
Post a Comment for "Django Csrf Token For Ajax"