我正在尝试使用fetch更新数据库项的内容。但是,我在控制台中得到403 Forbidden error。我没有在我的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);
})
})
}
});
我在views.py中添加了以下装饰器,它解决了这个问题:
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def edit_profile(request, member_id):
if request.method != "POST":
return JsonResponse({"error": "POST request required."}, status=400)
team_members = Team.objects.get(id = member_id)
body_unicode = request.body.decode('utf-8')
body = json.loads(body_unicode)
username = body['username']
skills = body['skills']
bio = body['bio']
Team.objects.filter(id=member_id).update(username=f'{username}',skills=f'{skills}',bio=f'{bio}')
return JsonResponse({"message": "Successful", "username": username, "skills": skills, "bio": bio}, status=200)