Django 403 Forbidden Error

When I try to use ajax on one page for html, it works. Like this:

<html>
    <head>
     ...
    </head>
    <body>
     ....
     <script>

    $.ajax({
        url: /test/,
        method: 'POST',
        headers: {'X-CSRFToken': '{{ csrf_token }}'},
        data: { name: a, surname: b},
        dataType: 'json',
        success: function (data) {
            getList(data);
        }
    });
    </script>
  </body>
</html>

When I try to use the same javascript as external. This does not work. What for?

<html>
    <head>
     ...
    </head>
    <body>
     ....
     <script src="{% static 'js/test.js' %}"></script>
  </body>
</html>
0
source share
1 answer

Define {{ csrf_token }}as a global variable on your HTML page in the tag scriptas a global variable as such: -

var generated_csrf_token = "{{ csrf_token }}";

And then in your .js file call it,

headers: {'X-CSRFToken': generated_csrf_token},

But make sure you put the AJAX call in the document ready func in $(document).ready(function () {***here***}

This way you can access it with a name generated_csrf_tokenin any js file.

Hope this helps :-)

+2
source

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


All Articles