2

样品表格:

class PayOrderedItemForm(forms.ModelForm):

    value_label = forms.CharField(widget = forms.HiddenInput())
    product_id = forms.ModelChoiceField(
                        queryset = Product.objects.all(),
                        widget = forms.HiddenInput())
    balance = forms.CharField(widget = forms.HiddenInput())
    class Meta:
        model = PayOrderedItem
        exclude = ('payorder_id', 'balance', 'value_label',)

POST 示例:

def PayOrderView (request, order_id):
...

    if request.method == "POST":
        poForm = PayOrderForm(request.POST)
        ##poItem = PayOrderedItemFormset(request.POST, request.FILES)
        formset = inlineformset_factory(
                        PayOrder,
                        PayOrderedItem,
                        form = PayOrderedItemForm,
                        can_delete=False)
        poItem = formset(request.POST, request.FILES)

        if poItem.is_valid() and poForm.is_valid() :
            poForm.save()
            print "poItem >> ", poItem
            poItem.save()
        else :
            print "invalid poItem", poItem.errors


        return HttpResponseRedirect(reverse('orderdetail', args=(order_id)))
    else :
        ## GET process

我想从 PayOrderedItemForm 中排除字段 value_label 和 balance,它总是在验证 poItem (poItem.is_valid) 时失败

以下错误是: 1. balance:此字段为必填项。2. value_label:此字段为必填项。

请帮助我正确的解决方案如何在验证中排除余额和 value_label。

4

1 回答 1

3

您可以使用required=False表示不需要的字段。例如:

field = forms.CharField(required=False)
于 2013-10-29T20:06:22.767 回答