Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: How can I create a multiple select form?

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!

like image 593
CodeArtist Avatar asked Mar 13 '13 18:03

CodeArtist


People also ask

Can we create multiple models in Django?

Creating ModelsA project can contain multiple apps. An app can be in multiple projects. We will create two models: Question and Choice.

How do I use MultipleChoiceField?

MultipleChoiceField in Django Forms is a Choice field, for input of multiple pairs of values from a field. The default widget for this input is SelectMultiple. It normalizes to a Python list of strings which you one can use for multiple purposes.


2 Answers

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>
like image 188
vibhor Avatar answered Sep 19 '22 01:09

vibhor


I did it in this way :

forms.py

class ChoiceForm(ModelForm):
    class Meta:
        model = YourModel

    def __init__(self, *args, **kwargs):
        super(ChoiceForm, self).__init__(*args, **kwargs)
        self.fields['countries'] =  ModelChoiceField(queryset=YourModel.objects.all()),
                                             empty_label="Choose a countries",)

urls.py

from django.conf.urls.defaults import * 
from django.views.generic import CreateView
from django.core.urlresolvers import reverse

urlpatterns = patterns('',
    url(r'^$',CreateView.as_view(model=YourModel, get_success_url=lambda: reverse('model_countries'),
        template_name='your_countries.html'), form_class=ChoiceForm, name='model_countries'),)

your_countries.html

<form action="" method="post">
    {% csrf_token %}
    {{ form.as_table }}
    <input type="submit" value="Submit" />
</form> 

It is works fine in my example, If you need something more, just ask me!!

like image 26
prog.Dusan Avatar answered Sep 19 '22 01:09

prog.Dusan