简体   繁体   English

如何在django中应用csrf_token

[英]how to apply csrf_token in django

In Django Template Without using form i want to upload files to my web server. 在Django模板中不使用表单我想将文件上传到我的Web服务器。 so for that i`m using javascript library called dropzonejs. 所以我使用名为dropzonejs的javascript库。

I exactly follow this tutorial bootstrap dropzonejs . 我正好遵循这个教程bootstrap dropzonejs I setup everything to run the demo. 我设置了一切来运行演示。

You see i decided not to use form so obviously the problem csrf_token is missing when upload happens time. 你看,我决定不使用form所以当上传发生的时候,问题csrf_token很明显。

My doubt is how to include csrf_token in javascript . 我怀疑的是如何在javascript包含csrf_token ?

This is the information they added in their home page for how to add csrf token 这是他们在主页中添加的有关如何添加csrf令牌的信息

sending - Called just before each file is sent. 发送 - 在每个文件发送之前调用。 Gets the xhr object and the formData objects as second and third parameters, so you can modify them (for example to add a CSRF token) or add additional data. 获取xhr对象和formData对象作为第二个和第三个参数,以便您可以修改它们(例如添加CSRF标记)或添加其他数据。

Are you understand my question ? 你明白我的问题吗? give me some idea to do that ? 给我一些想法吗?

You could either have the view CSRF exempt : 您可以拥有CSRF免除视图:

from django.views.decorators.csrf import csrf_exempt

class YourView(models.View):

    @csrf_exempt
    def dispatch(self, *args, **kwargs):
        return super(YourView, self).dispatch(*args, **kwargs)       

The JavaScript config would probably look something similar to this: JavaScript配置可能看起来与此类似:

(function($){
    $(function(){
      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;
    }
    var csrftoken = getCookie('csrftoken');

    function csrfSafeMethod(method) {
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    $.ajaxSetup({
        crossDomain: false,
        beforeSend: function(xhr, settings) {
            if (!csrfSafeMethod(settings.type)) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            }
        }
    });
  });
})(jQuery);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM