How to capture multiple HTML values with django forms

0

In order for html to send a field of type select with multiple values selected it is necessary to put the [] notation in the name attribute of html :

<select name="categories[]" multiple="multiple" class="form-input__select">
    {% for cat in categories %}
        <option value="{{ cat.id }}">{{ cat.id }}</option>
    {% endfor %}
</select>

How do I capture this value using% django%?

I tried using the:

categories = forms.MultipleChoiceField(required=False)

However when using Form.forms the value of form.cleaned_data is empty.

debug before categories[] :

'categories[]': ['AB', 'AU'], 'brands_are_inclusive': ['true']

debug after cleaned_data :

'categories': [], 'brands_are_inclusive': 'true'
    
asked by anonymous 26.09.2018 / 15:59

1 answer

0

In Django it is not necessary to use [] after the field name, you can remove this from your HTML.

The problem is that MultipleChoicesField requires a choices parameter that must be informed so that django can recognize the options. See in the documentation :

  

Takes one extra required argument , choices , as for ChoiceField .

An example that would work:

 categories = forms.MultipleChoiceField(required=False,
     choices=[('AB', 'Albânia'), ('AU', 'Austrália')])
    
26.09.2018 / 19:26