Select A Valid Choice Modelchoicefield
Whenever im running form.is_valid() i get the error: Select a valid choice. That choice is not one of the available choices. Here is what I do in my view: timeframes = HostTim
Solution 1:
According to documentation ModelChoiceField
its Default widget is Selectdoc
If you want to select multiple values you must use ModelMultipleChoiceField like this :
timeframes = forms.ModelMultipleChoiceField(queryset=HostTimeFrame.objects.none(), widget=forms.CheckboxSelectMultiple,empty_label=None)
Solution 2:
This seems to be a bug, my workaround was creating my own Choice field and overriding the to_python() method:
classCustomModelChoiceField(ModelChoiceField):
defto_python(self, value):
if value in self.empty_values:
returnNonetry:
key = self.to_field_name or'pk'#--------hacky bugfix---------------iftype(value) == list:
value = value[0]
value = self.queryset.get(**{key: value})
except (ValueError, TypeError, self.queryset.model.DoesNotExist):
raise ValidationError(self.error_messages['invalid_choice'], code='invalid_choice')
return value
Post a Comment for "Select A Valid Choice Modelchoicefield"