How to capture multiple HTML values with Django Forms

Asked

Viewed 101 times

0

So that the html send a field of the type select with several 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 Form.forms Django?

I tried to use the:

categories = forms.MultipleChoiceField(required=False)

but when using the form.cleaned_data the value of categories[] empty.

debug before the cleaned_data:

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

debug after the cleaned_data:

'categories': [], 'brands_are_inclusive': 'true'
  • Man, as far as I know this trick to use [] to denote multiple values is a PHP thing. On other servers just use name="categories" because sending to the server turns into something like: categories=1&categories=3&categories=5.

  • if I don’t put the [] the validation of MultipliChoiceField does not capture the field ie, is not a list

1 answer

0

No Django there’s no need use [] after the field name, you can remove this from your HTML.

The problem is that the MultipleChoicesField requires a parameter choices that has to 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')])
  • in my case the choices are not predefined, the user will send them through a form that uses a JS plugin.

  • @RFL So you need to somehow rescue these user values, maybe by ajax, or send them to the request in some way, before creating the MultipleChoicesField, For, if you want to use this class, it is mandatory to inform the options, as you can see in the documentation that I Linkei. Class does not work without passing this parameter.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.