如何在Django中验证Form中的某些字段

时间:2013-10-29 19:51:27

标签: python django

样本表格:

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和余额,它将在验证poItem时失败(poItem.is_valid)

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

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

1 个答案:

答案 0 :(得分:3)

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

field = forms.CharField(required=False)