Django:如何在使用ajax准备from时添加csrf令牌



我正在我的项目中添加注释功能。我使用ajax使其动态,这样当用户单击评论提交按钮时,它将动态添加到评论部分,而不刷新页面。但问题是,当使用ajax准备表单时,我无法添加像这样的csrf令牌

{% csrf_token %}

表单中,因为ajax不理解它并将其视为文本。

function getids(postid){
console.log(postid)
$(postformid).one('submit', function(event){
event.preventDefault();
console.log(event)
console.log("form submitted!")  // sanity check
create_comment(posted);
});
}
// AJAX for posting
function create_comment(postid) {
console.log("create comment is working!") // sanity check
console.log(postid)
console.log(talkid)
$.ajax({
url : "create_comment/"+postid, // the endpoint
type : "POST", // http method
data : { the_comment : $(cmtext).val() }, // data sent with the post request
// handle a successful response
success : function(json) {
$(cmtext).val(''); // remove the value from the input
console.log(json); // log the returned json to the console
$(talkid).prepend(
"<div class='col-1 p-0'><form' id=upvote' method='POST'>{%"csrf_token"%}<button 
class='btn btn-md btn-outline-danger btn- 
block p-auto' id='btnid' onclick='---' type='submit'></button></form></div>");
console.log("success"); // sanity check
},
// handle a non-successful response
error : function(xhr,errmsg,err) {
}
});
};

在这里假装我的表格

<div class="row m-0" id="talk{{post.id}}"></div>

周围还有别的路吗?

使用

{% csrf_token %}

就在模板中的表单标记之前。

最新更新