pythondjangodjango-formsdjango-select2

Django form doesn't validate when init ModelMultipleChoiceField without data


I want to use ModelMultipleChoiceField with select2 in my Django application.

this is forms.py :

#forms.py
class SymbolForm(forms.Form):
    symbol = forms.ModelMultipleChoiceField(queryset=Symbol.objects.all(), label='symbol')

Everything is ok except one thing. Symbol table has about 5 thousand record and when html rendered all data pass to html template. I don't want it.

I did change my form to this:

# forms.py
class SymbolForm(forms.Form):
    symbol = forms.ModelMultipleChoiceField(queryset=Symbol.objects.all(), label='symbol')
    def __init__(self, *args, **kwargs):
        super(SymbolForm, self).__init__(*args, **kwargs)
        self.fields['symbol'].queryset = Symbol.objects.none()

to init form without any data. A new problem arises: when form submitted, it is n't valid and django says that my chosen symbol doesn't valid choice.

In fact, my problem is that I want to create the form without the data and then be able to verify it with the data I get from the select2, but Django does not allow this.

What can I do?


Solution

  • By using this question and Sergio answer, I found out that I need to rewrite init method of form:

    self.fields['symbol'].queryset = Symbol.objects.none()
    if 'symbol' in self.data:
        try:
            symbols_ids_list = list(map(int,  self.data.getlist('symbol')))
            self.fields['symbol'].queryset = Symbol.objects.filter(pk__in=symbols_ids_list).order_by()
        except (ValueError, TypeError):
            pass