Submit MultipleChoiceField in Django with custom multiselect jQuery box

823 views Asked by At

I am trying to submit a multiple choice field using this jQuery plugin to render the multiple choices.

My form is as follows:

class BackupForm(forms.Form):
    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        super(BackupForm, self).__init__(*args, **kwargs)
        self.fields['contas_choice'] = forms.MultipleChoiceField(
            choices=get_backup_choices(self.user)
        )

        for field in self.fields:
            self.fields[field].widget.attrs.update({'class': 'form-control', })

        self.fields['contas_choice'].widget.attrs.update(
            {
                'name': 'from[]',
                'id': 'search',
                'class': 'form-control',
                'size': '8',
                'multiple': 'multiple',
            }
        )

    contas_choice = forms.MultipleChoiceField(required=False)
    # other fields

And on my template:

<form action="" class="form-horizontal" method="post">{% csrf_token %}
    <div class="row">
        <div class="col-xs-5">
            {% for choice in form.contas_choice %}
                {{ choice }}
            {% endfor %}
        </div>

        <div class="col-xs-2">
            <button type="button" id="search_rightAll" class="btn btn-block"><i
                    class="glyphicon glyphicon-forward"></i></button>
            <button type="button" id="search_rightSelected" class="btn btn-block"><i
                    class="glyphicon glyphicon-chevron-right"></i></button>
            <button type="button" id="search_leftSelected" class="btn btn-block"><i
                    class="glyphicon glyphicon-chevron-left"></i></button>
            <button type="button" id="search_leftAll" class="btn btn-block"><i
                    class="glyphicon glyphicon-backward"></i></button>
        </div>

        <div class="col-xs-5">
            <select name="to[]" id="search_to" class="form-control" size="8" multiple="multiple"></select>
        </div>
    </div>
    <div id="actions" class="row">
        <div class="col-md-12">
            <button type="submit" class="btn btn-primary">Baixar</button>
            <a href="/listar-contas/" class="btn btn-default">Cancelar</a>
        </div>
    </div>
</form>

This renders the select field just like I wanted, as in the example of the plugin reference.

But when I try to submit the form, I get an HTML message saying "Please select an item in the list", even after I have moved all the items to the right box. Therefore, I can't submit the form, and I don't even get any Django error, because it fails the HTML validation right away.

What should I do to make all the items on the right box be submitted?

Thanks!

0

There are 0 answers