Django - 禁用表单选择字段验证

时间:2015-05-07 11:13:40

标签: python django forms django-crispy-forms

我有一个表格让我先选择产品类型,然后选择产品。由于我有1000多种产品,因此我使用以下内容过滤产品列表以提高性能。

我在views.py

中有以下内联形式
OrderLineFormSet = inlineformset_factory(OrderHeader, OrderLine, OrderLineForm, extra = 1)

在我的forms.py中,我检查是否已选择产品。如果选择了产品,我只会显示具有相同产品类型的产品,以提高负载性能。如果产品为空,则会加载所有产品选项,以便在选择后保存表单。

class OrderLineForm(forms.ModelForm):

def __init__(self, *args, **kwargs):
    super(OrderLineForm, self).__init__(*args, **kwargs)
    self.helper = FormHelper(self)
    self.helper.form_show_errors = True
    self.helper.error_text_inline = False
    if self.instance.product is not None:        
        self.fields['product'] = forms.ModelChoiceField(queryset=Product.objects.filter(product_type_id=self.instance.product_type_id), required=False)

这导致以下形式

enter image description here

但是,当我更改现有表单上的Product类型(然后使用jQuery更新Product下拉列表)时,我会收到错误保存。我知道这是因为选择不是下拉列表中的一个选项。

enter image description here

我的问题:如何禁用此错误,以便保存我选择的选项,无论原始选项如何。

您将在下面找到此表单的views.py

def orderline_formset(request, id=None):

OrderLineFormSet = inlineformset_factory(OrderHeader, OrderLine, OrderLineForm, extra = 1)

orderheader = None
orderid = None
orderheaderid = 0

if id:
    orderid = OrderHeader.objects.get(pk=id)

if request.POST:
    if orderid:
        form = OrderHeaderForm(request.POST, instance=orderid)
        formset = OrderLineFormSet(request.POST,instance=orderid)
    else:
        form = OrderHeaderForm(request.POST)
        formset = OrderLineFormSet(request.POST)

    if form.is_valid() and formset.is_valid():
        if orderid:
            form.save()  # update object
        else:
            orderid = form.save()  # create object
        formset.instance = orderid
        formset.save()
        messages.success(request, 'Order saved succesfully!')
        return HttpResponseRedirect('/orderline_formset/' + str(orderid.pk))

    else:  # form invalid
        messages.error(request, 'Order save error, please check mandatory fields')


else:  # request.GET
    if orderid:
        invoiceheader = "" 
        if orderid.orderheader_invoice:
            invoiceheader = " -- Invoice " + str(orderid.orderheader_invoice) 
        orderheader = "Order " + str(orderid.pk) + invoiceheader

        orderheaderid = orderid.pk
        form = OrderHeaderForm(instance=orderid)
        formset = OrderLineFormSet(instance=orderid)
    else:
        orderheader = "New Order"
        orderheaderid = 0
        form = OrderHeaderForm(instance=OrderHeader())
        formset = OrderLineFormSet(instance=OrderHeader())

return render_to_response("order-add.html", {'form' : form,'formset': formset, 
                            'orderheader': orderheader,
                            'orderheaderid': orderheaderid},
                            context_instance=RequestContext(request))

4 个答案:

答案 0 :(得分:6)

覆盖ModelChoiceField,例如:

class MyModelChoiceField(ModelChoiceField):

   def to_python(self, value):
        try:
            value = super(MyModelChoiceField, self).to_python(value)
        except self.queryset.model.DoesNotExist:
            key = self.to_field_name or 'pk'
            value = Product.objects.filter(**{key: value})
            if not value.exists():
               raise ValidationError(self.error_messages['invalid_choice'], code='invalid_choice')
            else:
               value= value.first()
       return value

并在表单中使用它。

self.fields['product'] = MyModelChoiceField(queryset=Product.objects.filter(product_type_id=self.instance.product_type_id), required=False)

答案 1 :(得分:0)

你必须改变

    self.fields['product'] = forms.ModelChoiceField(queryset=Product.objects.filter(product_type_id=self.instance.product_type_id), required=False)

    self.fields['product'] = forms.ModelChoiceField(queryset=Product.objects.all(), required=False)

但是您已经知道并且出于性能原因不希望它,所以您的其他解决方案是将其更改为

self.fields['product'] = ModelChoiceField(queryset=Product.objects.all(),  widget=forms.HiddenInput, required=False)

然后在模板中手动构建<select>标记并使用JS句柄onchange事件并使其更新产品字段

答案 2 :(得分:0)

class OrderLineForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(OrderLineForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper(self)
        self.helper.form_show_errors = True
        self.helper.error_text_inline = False
        self.fields['product'] = forms.ModelChoiceField(
            queryset=Product.objects.all())
        self.fields['product'].required = False

在此之后,您可以使用jquery过滤器过滤选择。

答案 3 :(得分:0)

为Django 1.11更新@ruddra的答案:

    class DynamicModelChoiceField(ModelChoiceField):
    def to_python(self, value):
        try:
            value = super().to_python(value)
        except ValidationError:
            key = self.to_field_name or 'pk'
            value = self.queryset.model.objects.filter(**{key: value})
            if not value.exists():
                raise
            value = value.first()
        return value