formset表单字段中的keyerror

时间:2019-03-22 22:21:04

标签: javascript python html ajax django

我正在制作交货单交易表单,我创建了一个表单集,我希望Django忽略未选中且为空的项目交易。

forms.py

class Delivery_note_transiction_form(forms.Form):

    item = forms.CharField(widget=Select2Widget(attrs={"class" : "item"}),label=False,required=False)
    description = forms.CharField(widget=forms.TextInput(attrs={ 'placeholder' : 'optionall','class' : 'description'}),label=False,required=False)
    quantity = forms.IntegerField(widget=forms.NumberInput(attrs={'class' : 'quantity'}),label=False,min_value=1)
    id = forms.CharField(widget=forms.HiddenInput,required=False)

Delivery_note_transiction_form_formset = forms.formset_factory(Delivery_note_transiction_form,extra=1)

views.py

def feedback(request):
     if request.method == "POST" and request.is_ajax():
         form = Deliver_Note_Main_Modelform(request.POST)
         formset = Delivery_note_transiction_form_formset(request.POST,request.FILES)
    if form.is_valid() and formset.is_valid():

        ins = form.save(commit=False)
        ins.author = request.user

        result = Customer_data.objects.get(pk=form.cleaned_data['customer'])

        ins.customer_list = result
        ins.save()


        max_invoice = Invoice_max.objects.get(invoice_name='delivery')
        max_invoice.invoice_no = max_invoice.invoice_no + 1
        max_invoice.save()

        print(formset)
        for instant in formset:
            if instant.cleaned_data['item']:

                item = Product.objects.get(pk=instant.cleaned_data['item'])
                description = instant.cleaned_data['description']
                quantity = instant.cleaned_data['quantity']
                Delivery_Note_Transiction.objects.create(
                item=item,
                description=description,
                quantity=quantity,
                delivery_invoice_no=ins
            )

        return JsonResponse({'success':True, 'next' : reverse_lazy('delivery note:delivery note home page')})

    else:
        return render(request,"delivery_note/ajax/delivery note error message.html",{"error" : form, "transiction_error": formset})
return HttpResponse("Hello from feedback!")

template.html

{% for delivery in delivery_transiction %}
    <tr class=" delivery_form ">
        <td class="col-sm-4">{{ delivery.item|as_crispy_field }}</td>
        <td class="col-sm-4">{{ delivery.description|as_crispy_field }}</td>
        <td class="col-sm-4">{{ delivery.quantity|as_crispy_field }}</td>
    </tr>
{% endfor %}

帖子数据由Ajax发送,并在模板上创建选定的选项。加载后,Ajax将添加新行。问题是,如果未选中该项目或该项目为空,我希望它忽略交易记录,但是当我运行它时,会出现此错误:

  

“ KeyError:'item'”

它应该忽略空白或未选中的项目。仅当未在事务中选择该项目时才会发生这种情况。我想修复此错误,以便它只会忽略未选中该项目的行。

1 个答案:

答案 0 :(得分:1)

在字典中搜索密钥时,必须使用try except

for instant in formset:
    try:
        item = Product.objects.get(pk=instant.cleaned_data['item'])
    Except KeyError:
        # What to do if no 'item'.

您将必须弄清楚其余代码的放置位置,但这将使您超越KeyError