Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django csrf token for Ajax

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>
like image 732
Learning Django Avatar asked Aug 06 '18 05:08

Learning Django


People also ask

Is CSRF token necessary Django?

For all incoming requests that are not using HTTP GET, HEAD, OPTIONS or TRACE, a CSRF cookie must be present, and the 'csrfmiddlewaretoken' field must be present and correct. If it isn't, the user will get a 403 error.

Why CSRF token is not working Django?

If your view is not rendering a template containing the csrf_token template tag, Django might not set the CSRF token cookie. This is common in cases where forms are dynamically added to the page. To address this case, Django provides a view decorator which forces setting of the cookie: ensure_csrf_cookie() .

What is CSRF token in Django and why is that used?

Django features a percent csrf token percent tag that is used to prevent malicious attacks. When generating the page on the server, it generates a token and ensures that any requests coming back in are cross-checked against this token. The token is not included in the incoming requests; thus they are not executed.


2 Answers

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>
like image 179
ceds Avatar answered Sep 17 '22 15:09

ceds


The documentation very well explained how to use AJAX https://docs.djangoproject.com/en/2.1/ref/csrf/

  1. Get this library https://github.com/js-cookie/js-cookie/
  2. Add this var csrftoken = Cookies.get('csrftoken');
  3. 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);
        }
      }
    });
    
like image 42
Krystian Kazimierczak Avatar answered Sep 20 '22 15:09

Krystian Kazimierczak