[Fixed]-Django – Disable form select field validation

11👍

Override ModelChoiceField, for example:

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

And use it in your form.

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

2👍

Updating @ruddra ‘s answer for Django 1.11:

    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

1👍

You must change

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

To

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

But you already know that and don’t want it for performance reasons so your other solution is changing it to

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

then inside your template you manually construct your <select> tag and using JS handle onchange event and make it update the product field

👤Ramast

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

After this you can filter select with jquery filters.

Leave a comment