The post request of Django calling external js file appears 403

Keywords: Django JQuery

Today, I found an interesting problem. The function of writing js code in html works normally, but there are various problems when js code is put into js file.

1. When using jQuery to dynamically generate tags, it is recommended to put the js file written by yourself after < / body >
(otherwise, some functions may fail)

2 as shown in the question, error 403 occurs because django has a csrf mechanism. If there is no csrf authentication, access will be blocked. There are two solutions:
(1) Find the following code in the settings.py file

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    # This mechanism may not be used on this statement comment (but is not recommended)
    # 'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
)

(2) The second way is to add csrf verification, which is divided into three situations:
a. When submitting the form, add the following code under the form form form:

<form method="POST" action="#">
    {% csrf_token %}
</form>

b. When writing js code in html, you can use this method:

<script>
    $.ajaxSetup({
        data: {csrfmiddlewaretoken: '{{ csrf_token }}' },
    });
</script>

c. When HTML calls js file externally, you need to add the following code to js file:

jQuery(document).ajaxSend(function(event, xhr, settings) {
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    function sameOrigin(url) {
        // url could be relative or scheme relative or absolute
        var host = document.location.host; // host + port
        var protocol = document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relative URLs to same origin
        return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            // or any other URL that isn't scheme relative or absolute i.e relative.
            !(/^(\/\/|http:|https:).*/.test(url));
    }
    function safeMethod(method) {
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});

Here, I refer to some blog posts on the Internet, and then summarize them according to my own practice.

Posted by Nexy on Fri, 03 Apr 2020 19:00:08 -0700