选择一个有效的选择ModelChoiceField [英] Select a valid choice ModelChoiceField

查看:113
本文介绍了选择一个有效的选择ModelChoiceField的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我运行form.is_valid()我得到错误:

Whenever im running form.is_valid() i get the error:


选择一个有效的选择。这个选择不是可用的
选项之一。

Select a valid choice. That choice is not one of the available choices.

这是我在我的看法:

timeframes = HostTimeFrame.objects.all()
if request.method == 'POST':
    form = SelectDatesForm(request.POST, timeframes=timeframes)
    if form.is_valid():
        pass
else:
    form = SelectDatesForm(timeframes=timeframes)

我的表单这样做:

 class SelectDatesForm(forms.Form):
    timeframes = forms.ModelChoiceField(queryset=HostTimeFrame.objects.none(), widget=forms.CheckboxSelectMultiple,
                                        empty_label=None)
    def __init__(self, *args, **kwargs):
        qs = kwargs.pop('timeframes')
        super(SelectDatesForm, self).__init__(*args, **kwargs)
        self.fields['timeframes'].queryset = qs.order_by('start')

几个小时,找到这个实际验证完成的地方,我发现它造成了一个错误这里

Ive been trying for hours to find where this actual validation is done, and i found it, created a bug here.

推荐答案

根据文档 ModelChoiceField 其默认小部件是选择 doc

According to documentation ModelChoiceField its Default widget is Select doc

如果要选择多个值,您必须使用 ModelMultipleChoiceField 这样:

If you want to select multiple values you must use ModelMultipleChoiceField like this :

timeframes = forms.ModelMultipleChoiceField(queryset=HostTimeFrame.objects.none(), widget=forms.CheckboxSelectMultiple,empty_label=None)

这篇关于选择一个有效的选择ModelChoiceField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆