jquery - Django AJAX 'GET' 表单 csrf_token 不适用于 'POST'
问题描述
我正在加载form
一个template
with AJAX
。我已经{% csrf_token %}
在模板中包含了 a ,但是当我POST
使用时form
,我得到了csrf error
屏幕。我尝试了一些我见过的不同的东西,但它没有奏效。
原观点:
def customer_profile(request, pk):
name = get_object_or_404(CEName, id=pk)
return render(
request,
'customer/customer_profile.html',
{'profile_name': name}
)
原始模板:
{% block content %}
{% include 'ce_profiles/name_header.html' %}
<div id="name" class="container d-flex justify-content-between pt-1">
{% include 'ce_profiles/profile_name.html' %}
<button id="update_button" action="{% url 'ce_profiles:profile-update-name' profile_name.id %}" class="bold btn btn-main btn-sm button-main">UPDATE</button>
</div>
<div id="div_NameForm" class="container">
</div>
{% endblock %}
{% block script %}
<script src="{% static 'ce_profiles/ce_profiles.js' %}"></script>
{% endblock %}
脚本.js
$(document).ready(function() {
$("#NameForm").submit(function(event) {
event.preventDefault();
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: $(this).serialize(),
dataType: 'json',
success: function(data) {
$('#profile_name').html(data.profile_name);
}
});
});
});
let updateButton
let toggleNameForm = function(e) {
e.stopPropagation();
let btn = this;
if (btn.innerHTML === "UPDATE") {
$.ajax({
url: $(this).attr('action'),
type: 'GET',
dataType: 'json',
success: function(data) {
$('#div_NameForm').html(data.NameForm);
}
});
btn.innerHTML = "CANCEL";
btn.classList.replace("button-main", "button-secondary");
} else {
$('#div_NameForm').html('<div id="div_NameForm" class="container"></div>');
btn.innerHTML = "UPDATE";
btn.classList.replace("button-secondary", "button-main");
}
};
document.addEventListener('DOMContentLoaded', function () {
updateButton = document.getElementById('update_button');
updateButton.addEventListener('click', toggleNameForm);
});
表单视图和模板:
def profile_update_name(request, pk):
name = get_object_or_404(CEName, id=pk)
if request.POST:
name_form = NameForm(data=request.POST, instance=name)
if name_form.has_changed() == False:
name_form.add_error(None, _('No changes made.'))
if name_form.is_valid():
name_form.save()
updated_name = get_object_or_404(CEName, id=name.id)
profile_name_json = render_to_string(
'ce_profiles/profile_name.html',
{'profile_name': updated_name,}
)
return JsonResponse({'profile_name': profile_name_json})
else:
return JsonResponse({'error': name_form.errors})
else:
name_form = NameForm(instance=name)
get_NameForm_json = render_to_string(
'ce_profiles/update_NameForm.html',
{'NameForm': name_form, 'profile_name': name}
)
return JsonResponse({'NameForm': get_NameForm_json})
<hr size="3px">
<form id="NameForm" method="POST" action="{% url 'ce_profiles:profile-update-name' profile_name.id %}">
{% csrf_token %}
{{ NameForm.as_p }}
<div id="NameForm_errors"></div>
<br>
<button id="save_changes" type="submit" class="btn btn-main button-main btn-block">Save Changes</button>
</form>
解决方案
所以事实证明我必须将 . 添加request
到 中,render_to_string
因为我的AJAX
调用没有呈现{% csrf_token %}
. 我的视图现在看起来像:
else:
name_form = NameForm(instance=name)
get_NameForm_json = render_to_string(
'ce_profiles/update_NameForm.html',
{'NameForm': name_form, 'profile_name': name},
# added 'request'
request=request
)
return JsonResponse({'NameForm': get_NameForm_json})
推荐阅读
- python - Seaborn 不接受日期时间值
- excel-formula - 需要帮助计算 ID 在按月列中重复的次数
- networking - 如何确定 windows server 2016 上的总网络带宽使用情况?
- android - Android connectedAndroidTest failed with com.android.ddmlib.InstallException: Unknown failure (Error: failed to write;(No such file or directory))
- google-sheets - 谷歌查询功能错误过滤数据
- javascript - 如何在多个动态元素上使用 Jquery .on() 方法?
- ruby-on-rails - 如何从下拉选择器中渲染同一模型的不同实例?
- php - GMAIL 在使用 file_get_contents 时显示消息被剪裁
- haskell - Haskell 函数是高阶的当且仅当它的类型有多个箭头?
- javascript - 为什么我收到 TypeError 无法读取我定义的数组和对象的未定义属性“移动”?