ModelMultipleChoiceField - override validation

154 views
Skip to first unread message

Earl Lapus

unread,
Nov 19, 2021, 7:38:47 PM11/19/21
to Django users
Hi,

I have a ModelForm that has a ModelMultipleChoiceField. In the said field, I've set the queryset to none and assigned the FilteredSelectMultiple as the widget for the field.

It looks like this:

class MyForm(forms.ModelForm):
    myfield = ModelMultipleChoiceField(
        queryset=SomeModel.objects.none(),
        widget=admin.widgets.FilteredSelectMultiple('SomeModel', False),
        required=False
    )

I added some javascript on the template to dynamically add items to the widget based on a value from another field. That part already works. But, I am running into an error during submit - validation error. An example error I get is: "Select a valid choice. 4 is not one of the available choices."  This is expected since I've set the queryset to be empty, so values will match during validation.

Where should I override the validation? I tried creating a ModelMultipleChoiceField child class and implemented the `to_python()` method but it seems like that method is not called. Is there any documentation that can help me arrive at an answer for this?

Cheers,
Earl

Earl Lapus

unread,
Nov 22, 2021, 9:14:16 AM11/22/21
to Django users
I was able to resolve this by overriding `clean()` instead of `to_python()`. In there, I've the set correct queryset to use for validation.

I still could not explain why `to_python()` is not called.
Reply all
Reply to author
Forward
0 new messages