Python Django:如何创建多选表单?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15393134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Django: How can I create a multiple select form?
提问by CodeArtist
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.
我是 Django/Python 的初学者,我需要创建一个多选表单。我知道这很容易,但我找不到任何例子。我知道如何使用小部件创建 CharField,但我对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:
还有一个小问题。如果我想为每个选项添加一个像data这样的属性:
<option value="AUT" selected="selected" data-index=1>Austria</option>
How can I do it?
我该怎么做?
Thanks for any help!
谢谢你的帮助!
采纳答案by vibhor
I think CheckboxSelectMultipleshould work according to your problem.
我认为CheckboxSelectMultiple应该根据您的问题工作。
In your forms.py, write the below code:
在您的 中forms.py,编写以下代码:
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:
在您的 中views.py,定义以下函数:
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:
在您的render_country.html:
<form method='post'>
{% csrf_token %}
{{ form.as_p }}
<input type='submit' value='submit'>
</form>
回答by Brandon
ModelMultipleChoiceFieldis your friend. A CharField is capable of storing one selection, but not multiple, without some extra work, which I would recommend against.
ModelMultipleChoiceField是您的朋友。CharField 能够存储一个选择,但不能存储多个,无需一些额外的工作,我建议不要这样做。
回答by prog.Dusan
I did it in this way :
我是这样做的:
forms.py
表格.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
网址.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
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!!
在我的例子中它工作正常,如果你需要更多的东西,问我!!
回答by CodeArtist
Regarding to my second question this is the solution. An extending class:
关于我的第二个问题,这是解决方案。扩展类:
from django import forms
from django.utils.encoding import force_unicode
from itertools import chain
from django.utils.html import escape, conditional_escape
class Select(forms.Select):
"""
A subclass of Select that adds the possibility to define additional
properties on options.
It works as Select, except that the ``choices`` parameter takes a list of
3 elements tuples containing ``(value, label, attrs)``, where ``attrs``
is a dict containing the additional attributes of the option.
"""
def render_options(self, choices, selected_choices):
def render_option(option_value, option_label, attrs):
option_value = force_unicode(option_value)
selected_html = (option_value in selected_choices) and u' selected="selected"' or ''
attrs_html = []
for k, v in attrs.items():
attrs_html.append('%s="%s"' % (k, escape(v)))
if attrs_html:
attrs_html = " " + " ".join(attrs_html)
else:
attrs_html = ""
return u'<option value="{0}"{1}{2}>{3}</option>'.format(
escape(option_value), selected_html, attrs_html,
conditional_escape(force_unicode(option_label))
)
'''
return u'<option value="%s"%s%s>%s</option>' % (
escape(option_value), selected_html, attrs_html,
conditional_escape(force_unicode(option_label)))
'''
# Normalize to strings.
selected_choices = set([force_unicode(v) for v in selected_choices])
output = []
for option_value, option_label, option_attrs in chain(self.choices, choices):
if isinstance(option_label, (list, tuple)):
output.append(u'<optgroup label="%s">' % escape(force_unicode(option_value)))
for option in option_label:
output.append(render_option(*option))
output.append(u'</optgroup>')
else:
output.append(render_option(option_value, option_label,
option_attrs))
return u'\n'.join(output)
class SelectMultiple(forms.SelectMultiple, Select):
pass
Example:
例子:
OPTIONS = [
["AUT", "Australia", {'selected':'selected', 'data-index':'1'}],
["DEU", "Germany", {'selected':'selected'}],
["NLD", "Neitherlands", {'selected':'selected'}],
["USA", "United States", {}]
]
回答by Navjot Gwal
You can also define countries field in your form class as
您还可以将表单类中的国家/地区字段定义为
Countries = forms.MultipleChoiceField(widget=forms.SelectMultiple,
choices=OPTIONS_TUPPLE)
I don't know which one is better in SelectMultiple and CheckboxSelectMultiple but it also works.
我不知道 SelectMultiple 和 CheckboxSelectMultiple 哪个更好,但它也有效。
For more details you can use django documentation about widgets.
有关更多详细信息,您可以使用有关小部件的django 文档。

