Django: How can I create a multiple select form?

CodeArtist picture CodeArtist · Mar 13, 2013 · Viewed 95.1k times · Source

I'm beginner in Django/Python and I need to create a multiple select form. I know it's easy but I can't find any example. I know how to create a CharField with a widget but I get confused of all the options inside fields.py.

For example I don't know which one of the followings is best for a multiple select form.

'ChoiceField', 'MultipleChoiceField',
'ComboField', 'MultiValueField',
'TypedChoiceField', 'TypedMultipleChoiceField'

And here is the form I need to create.

        <form action="" method="post" accept-charset="utf-8">
        <select name="countries" id="countries" class="multiselect" multiple="multiple">
            <option value="AUT" selected="selected">Austria</option>
            <option value="DEU" selected="selected">Germany</option>
            <option value="NLD" selected="selected">Netherlands</option>
            <option value="USA">United States</option>
        </select>
        <p><input type="submit" value="Continue &rarr;"></p>
    </form>

EDIT:

One more small question. If I want to add to each option one more attribute like data:

 <option value="AUT" selected="selected" data-index=1>Austria</option>

How can I do it?

Thanks for any help!

Answer

vibhor picture vibhor · Mar 13, 2013

I think CheckboxSelectMultiple should work according to your problem.

In your forms.py, write the below code:

from django import forms


class CountryForm(forms.Form):
    OPTIONS = (
        ("AUT", "Austria"),
        ("DEU", "Germany"),
        ("NLD", "Neitherlands"),
    )
    Countries = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,
                                          choices=OPTIONS)

In your views.py, define the following function:

def countries_view(request):
    if request.method == 'POST':
        form = CountryForm(request.POST)
        if form.is_valid():
            countries = form.cleaned_data.get('countries')
            # do something with your results
    else:
        form = CountryForm

    return render_to_response('render_country.html', {'form': form},
                              context_instance=RequestContext(request))

In your render_country.html:

<form method='post'>
    {% csrf_token %}
    {{ form.as_p }}
    <input type='submit' value='submit'>
</form>