我已經遍地搜索,但我無法解決它。我的頁面中有一個formset(底部的表格)。當我使用ajax按下保存按鈕時,主窗體和formset需要保存。 POST請求已發送但出現錯誤。管理表單數據丟失或已被篡改驗證表格
ERROR 「POST /新/ HTTP/1.1」 500 59
ValidationError:[u'ManagementForm數據丟失或已被篡改']
Views.py
def master_detail_new(request):
if request.method == 'GET':
author = TmpPlInvoice()
author_form = TmpForm(instance=author)
BookFormSet = inlineformset_factory(TmpPlInvoice, TmpPlInvoicedet,
exclude=('emp_id', 'voucher', 'lineitem', 'id',),
form=TmpFormDetForm,)
formset = BookFormSet(instance=author)
return render(request, 'main.html',
{'form': author_form, 'formset': formset, 'formtotal': totalform, 'postform': postform},
)
elif request.method == 'POST':
def get_new_voucher_id():
temp_vid = TmpPlInvoice.objects.order_by().values_list("voucher_id", flat=True).distinct()
if not temp_vid:
voucher_id = str(1).zfill(4)
else:
voucher_id = str(int(max(temp_vid)) + 1).zfill(4)
return voucher_id
author_form = TmpForm()
author = TmpPlInvoice()
BookFormSet = inlineformset_factory(TmpPlInvoice, TmpPlInvoicedet, exclude=('emp_id', 'voucher', 'lineitem', 'id',),
form=TmpFormDetForm, extra=2)
formset = BookFormSet(instance=author)
voucher_id = get_new_voucher_id()
author = TmpForm(request.POST)
if author.is_valid():
created_author = author.save(commit=False)
created_author.voucher_id = voucher_id
created_author.save()
formset = BookFormSet(request.POST, instance=created_author)
if formset.is_valid():
formset.save()
return HttpResponseRedirect('/')
HTML
<div class="x_content">
{{ formset.management_form }}
{{ formset.non_form_errors.as_ul }}
<table class="table table-striped responsive-utilities jambo_table bulk_action form"
id="formset" style="background-color:#d0ffff;">
<thead style="background-color:#9df0e0;;color: #73879C">
{% for form in formset.forms %}
{% if forloop.first %}
<thead>
<tr class="headings">
{% for field in form.visible_fields %}
<th>{{ field.label|capfirst }}</th>
{% endfor %}
</tr>
</thead>
{% endif %}
Javascript功能來發送數據
$("#save").click(function() {
$.ajax({
type:'POST',
url:'/new/',
data:{
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
},
success:searchSuccess,
dataType: 'html'
});
});
function searchSuccess(data, textStatus, jqXHR)
{
$('#myForm').html(data);
}
我到底做錯了什麼?任何幫助將不勝感激。 Multiple formsets
編輯 我沒有改變表單集數。我的CSRF工作正常。此外,我沒有ajax得到同樣的問題。
<input id="id_tmpplinvoicedet_set-TOTAL_FORMS" name="tmpplinvoicedet_set-TOTAL_FORMS" type="hidden" value="3" />
<input id="id_tmpplinvoicedet_set-INITIAL_FORMS" name="tmpplinvoicedet_set-INITIAL_FORMS" type="hidden" value="0" />
<input id="id_tmpplinvoicedet_set-MIN_NUM_FORMS" name="tmpplinvoicedet_set-MIN_NUM_FORMS" type="hidden" value="0" />
<input id="id_tmpplinvoicedet_set-MAX_NUM_FORMS" name="tmpplinvoicedet_set-MAX_NUM_FORMS" type="hidden" value="1000" />
你確定你傳入的csrf標記是正確的嗎? – Bono
您是否使用javascript來更改formset中窗體的數量? – schwobaseggl
如果您提交沒有Ajax的表單,它會工作嗎?它看起來好像你的'data'包含csrf標記,但沒有別的。 – Alasdair