我的模板文件中有一个表单,如此
<form action="#" id="details" class="inline">
{% csrf_token %}
{% for field in practice_form %}
<div class="container">
<div class="row">
<div class="form-group col-md-12">
{{field.label_tag}}
{{field}}
</div>
</div>
</div>
{% endfor %}
<div class="container">
<div class="row">
<input type="submit" id="save-practice" class="btn btn-primary" value="Save Details">
</div>
</div>
</form>
我的js
$("#save-practice").on('click', function (event){
event.preventDefault();
var form = $(this).parent();
$.ajax({
url: '/settings/add-practice-data/',
type: 'POST',
dataType: 'json',
data: form.serialize(),
success: function (data, status, jqXHR){
if (! data['success']){
form.trigger('reset');
alert("Something went wrong, Please try saving practice again.");
}
}
});
});
和django视图
def add_practice_details(request):
practice = PracticeData.objects.all()
data = {}
if request.method == 'POST' and request.is_ajax():
if practice:
form = PracticeDataForm(request.POST, instance=practice[0])
else:
form = PracticeDataForm(request.POST)
if form.is_valid():
practice_data = form.save()
data = dict(success=True)
else:
data = dict(success=False)
return HttpResponse(json.dumps(data, cls=DjangoJSONEncoder), content_type="application/json")
else:
raise PermissionDenied
视图检查是否有已保存的数据,以便编辑它们或创建新数据。但是我收到403错误。我在模板html文件中导入了csrf_token。什么可能是错的?