我有一个Django应用程序,并希望在用户的配置文件中显示多个选项复选框.然后他们将能够选择多个项目.
这是我的models.py的简化版本:
from profiles.choices import SAMPLE_CHOICES
class Profile(models.Model):
user = models.ForeignKey(User, unique=True, verbose_name_('user'))
choice_field = models.CharField(_('Some choices...'), choices=SAMPLE_CHOICES, max_length=50)
Run Code Online (Sandbox Code Playgroud)
我的表格类:
class ProfileForm(forms.ModelForm):
choice_field = forms.MultipleChoiceField(choices=SAMPLE_CHOICES, widget=forms.CheckboxSelectMultiple)
class Meta:
model = Profile
Run Code Online (Sandbox Code Playgroud)
和我的views.py:
if request.method == "POST":
profile_form = form_class(request.POST, instance=profile)
if profile_form.is_valid():
...
profile.save()
return render_to_response(template_name, {"profile_form": profile_form,}, context_instance=RequestContext(request))
Run Code Online (Sandbox Code Playgroud)
我可以看到POST只发送一个值:
choice_field u'choice_three'
Run Code Online (Sandbox Code Playgroud)
当地的vars params正在发送一份清单:
[u'choice_one', u'choice_two', u'choice_three']
Run Code Online (Sandbox Code Playgroud)
所有表单字段都显示正确,但是当我提交POST时,我收到错误
错误绑定参数7 - 可能不受支持的类型.
我是否需要在视图中进一步处理多选字段?模型字段类型是否正确?任何帮助或参考将不胜感激.
我希望用户能够通过管理界面进行多项选择,并将结果存储为逗号分隔值列表.选择多个或复选框列表会很棒.但是,我不需要这个值列表中的项目来特别引用任何模型......我只想要一个简单明了的项目文本列表,因此我不认为ManyToManyField是我的那个我正在寻找.在Django中最快的方法是什么?
如何从呈现的选项中删除“------”?我在我的模型形式中使用:
widgets = {
'event_form': forms.CheckboxSelectMultiple(),
}
Run Code Online (Sandbox Code Playgroud)
在模型中,我有 IntegerField 有选择:
EVENT_FORM_CHOICES = (
(1, _(u'aaaa')),
(2, _(u'bbbb')),
(3, _(cccc')),
(4, _(u'dddd')),
(5, _(eeee'))
)
Run Code Online (Sandbox Code Playgroud)
呈现的选择包含 --------- 作为第一可能的选择。我怎样才能摆脱它?
编辑:我想出的唯一工作方法是(在init方法中):
tmp_choices = self.fields['event_form'].choices
del tmp_choices[0]
self.fields['event_form'].choices = tmp_choices
Run Code Online (Sandbox Code Playgroud)
但这不是很优雅的方式:)