有人可以帮我解决这个问题吗?
我的页面中有任务列表。每个任务都有自己的表单,用户可以在其中发送评论。当我添加新任务AJAX更新评论列表然后我尝试按表单发送评论时它会引发错误:“CSRF令牌丢失或不正确”。在任何其他情况下,表格运作良好。我的表格中有{% csrf_token %}
。好像我需要在AJAX中发送CSRF。我错在哪里?为什么它不起作用?
JS:
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');
// TASK
$(function () {
var loadForm = function () {
var btn = $(this);
$.ajax({
url: btn.attr("data-url"),
type: 'get',
dataType: 'json',
beforeSend: function () {
$("#modal").modal("show");
},
success: function (data) {
$("#modal .modal-content").html(data.html_task_form);
}
});
};
var saveForm = function () {
var form = $(this);
$.ajax({
url: form.attr("action"),
data: {
data: form.serialize(),
csrfmiddlewaretoken: getCookie('csrftoken')
},
type: form.attr("method"),
dataType: 'json',
success: function (data) {
if (data.form_is_valid) {
$("#task-list").html(data.html_task);
$("#modal").modal("hide");
}
else {
$("#modal .modal-content").html(data.html_task_form);
}
}
});
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
return false;
};
// Create TASK
$("#task-add-button").click(loadForm);
$("#modal").on("submit", ".js-task-add-form", saveForm);
// Update TASK
$("#task-list").on("click", "#js-edit-task-button", loadForm);
$("#modal").on("submit", ".js-task-edit-form", saveForm);
});
评论代码添加:
views.py:
def task_comment_add(request, project_code, task_code):
data = dict()
project = get_object_or_404(Project, pk=project_code)
task = get_object_or_404(Task, pk=task_code)
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.author = request.user
comment.save()
task.comments.add(comment)
data['form_is_valid'] = True
data['html_task_comment'] = render_to_string('project/task_comment_list.html' {'task': group_task})
else:
data['form_is_valid'] = False
else:
form = CommentForm()
context = {'project': project, 'task': task, 'form': form}
data['html_task_comment_form'] = render_to_string('project/task_comment_form.html', context, request=request)
return JsonResponse(data)
JS:
// TASK COMMENT ADD
$(".task-comment-form").submit(function(event) {
event.preventDefault();
console.log(event.preventDefault());
var form = $(this);
$.ajax({
url: form.attr("action"),
data: form.serialize(),
type: form.attr("method"),
dataType: 'json',
success: function (data) {
var current_group = form.closest('.custom-list-group');
if (data.form_is_valid) {
current_group.find(".task-comments").html(data.html_task_comment);
}
else {
current_group.find(".task-comment-form").html(data.html_task_comment_form);
}
}
});
form[0].reset();
return false;
});
答案 0 :(得分:0)
尝试添加此
$.ajaxSetup(
{
headers:
{
'X-CSRF-Token': $('input[name="_token"]').val()
}
});
答案 1 :(得分:0)
您没有在Ajax请求上设置令牌:
https://docs.djangoproject.com/en/1.11/ref/csrf/#setting-the-token-on-the-ajax-request
在getCookie()调用后将其添加到您的代码中:
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});