Django - Disable form select field validation
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)
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