如何使用Django将CSRF令牌发送到ajax请求?

时间:2020-08-16 09:10:47

标签: python django flask django-models

我想在Django中的Ajax请求中发送csrf令牌。我不知道该怎么做。我有以下代码。

在我的html文件中,我有一个按钮

    <div class="col-md-6 col-sm-12 text-right" id="button_div">
            <a href="#" id="add_data" class="btn btn-primary">Add</a>
    </div>

    <div id="dynamic_table">
      /*some html*/
    </div> 

当我单击“添加”按钮时,我会清空“ dynamic_table”,并将我的联系表单代码附加到“ dynamic_table” div中。
联系人表格代码为

<form>
   <input type="text" name="fname">
   <input type="text" name="lname">
   <input type="button" name="send" value="send">
</form>

为此,我正在使用以下代码

$(document).on('click','#add_data',function(){
    $("#dynamic_table").empty();
    $("#dynamic_table").append('<form><input type="text" name="fname"><input type="text" name="lname"><input type="button" name="send" id="form_save" value="send"></form>');
});

直到现在,它仍然可以正常工作,但是当我从我的联系表单中单击“ form_save”按钮时

$(document).on('click','#save_btn',function(){
alert('hello')
})

我正在关注错误

 Forbidden (403)
    CSRF verification failed. Request aborted.
Reason given for failure:

    CSRF token missing or incorrect.
    
In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure:

Your browser is accepting cookies.
The view function passes a request to the template's render method.
In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.
If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data.
The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because the token is rotated after a login.
You're seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, and only the initial error message will be displayed.

You can customize this page using the CSRF_FAILURE_VIEW setting.

我是Django的新手。任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

我认为您可以将表单作为普通表单放置在div。#dynamic_table内,但使其不可见,而JS部分仅使其再次可见并提交即可。这样,我认为您可以将{%csrf_token%}重新返回到模板,并且没有csrf问题。