Opened 8 years ago

Last modified 8 years ago

#27578 closed Bug

ModelChoiceField.to_python() somehow receives value as type 'list' — at Initial Version

Reported by: Julian Owned by: nobody
Component: Forms Version: 1.9
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

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 realized the exception is raised in ModelChoiceField.to_python()

        try:
            key = self.to_field_name or 'pk'
            value = self.queryset.get(**{key: value})
        except (ValueError, TypeError, self.queryset.model.DoesNotExist):
            raise ValidationError(self.error_messages['invalid_choice'], code='invalid_choice')

Where value is the primary key, but in List format, this raises and exception.

Change History (0)

Note: See TracTickets for help on using tickets.
Back to Top