0

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 = HostTimeFrame.objects.all()
if request.method == 'POST':
    form = SelectDatesForm(request.POST, timeframes=timeframes)
    if form.is_valid():
        pass
else:
    form = SelectDatesForm(timeframes=timeframes)

My form does this:

 class SelectDatesForm(forms.Form):
    timeframes = forms.ModelChoiceField(queryset=HostTimeFrame.objects.none(), widget=forms.CheckboxSelectMultiple,
                                        empty_label=None)
    def __init__(self, *args, **kwargs):
        qs = kwargs.pop('timeframes')
        super(SelectDatesForm, self).__init__(*args, **kwargs)
        self.fields['timeframes'].queryset = qs.order_by('start')

Ive been trying for hours to find where this actual validation is done, and i found it, created a bug here.

Julian
  • 915
  • 8
  • 24

2 Answers2

5

According to documentation ModelChoiceField its Default widget is Select doc

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)
Messaoud Zahi
  • 1,214
  • 8
  • 15
1

This seems to be a bug, my workaround was creating my own Choice field and overriding the to_python() method:

class CustomModelChoiceField(ModelChoiceField):
    def to_python(self, value):
        if value in self.empty_values:
            return None
        try:
            key = self.to_field_name or 'pk'
            #--------hacky bugfix---------------
            if type(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
Julian
  • 915
  • 8
  • 24