我尝试使用fetch更新数据库项的内容。但是,我在控制台中收到403禁止错误。我没有在HTML模板中使用表单,只是将元素附加到div。日志显示CSRF令牌丢失。
document.addEventListener("DOMContentLoaded", function(){
const button = document.querySelectorAll("#edit_profile")
button.forEach(function(button){
button.onclick = function(){
const memberID = button.dataset.id;
const usernameID = button.dataset.username;
const username = document.getElementById(`username_${memberID}`);
let edit_username = document.createElement("textarea");
edit_username.setAttribute("rows", "1");
edit_username.innerHTML = username.innerHTML
edit_username.id = `edit_username_${memberID}`;
edit_username.className = `form-control username ${usernameID}`;
const saveButton = document.createElement("button");
saveButton.innerHTML = "Save";
saveButton.id = `saveButton_${memberID}`;
saveButton.className = "btn btn-success col-3";
saveButton.style.margin = "10px";
document.getElementById(`edit_${memberID}`).append(edit_username);
document.getElementById(`edit_${memberID}`).append(saveButton);
saveButton.addEventListener("click", function(){
edit_username = document.getElementById(`edit_username_${memberID}`);
fetch(`/edit_profile/${memberID}`,{
method: "POST",
body: JSON.stringify({
username: edit_username.value,
})
})
.then(response => response.json())
.then(result => {
console.log(result);
if(result[`error`]){
reset(memberID)
}
else {
username.innerHTML = result.username;
reset(memberID)
}
})
.catch(error => {
console.error(error);
})
})
}
});
1条答案
按热度按时间wqlqzqxt1#
我在www.example.com中添加了以下装饰器views.py,它解决了这个问题: