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 →"></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!
I think CheckboxSelectMultiple should work. According to your problem, In your forms.py wirite the below code
EDIT : I thought of writing complete code flow So that you can understand it better. Because you might get confuse
In your Views.py define the following function
In your render_country.html
I hope this helps.Let me know if it that is what you were expecting.
You can also define countries field in your form class as
I don't know which one is better in SelectMultiple and CheckboxSelectMultiple but it also works.
For more details you can use django documentation about widgets.
I did it in this way :
forms.py
urls.py
your_countries.html
It is works fine in my example, If you need something more, just ask me!!
ModelMultipleChoiceField is your friend. A CharField is capable of storing one selection, but not multiple, without some extra work, which I would recommend against.
API doc for ModelMultipleChoiceField
Regarding to my second question this is the solution. An extending class:
Example: