ModelChoiceField在表单提交时给出无效选择错误

时间:2012-05-28 18:06:57

标签: django django-forms

我想允许用户删除特定型号的关联外键列表。

假设我们有这两个模型:


class IceBox(models.Model):
    ...

class FoodItem(models.Model):
    name = models.CharField(...)
    icebox = models.ForeignKey(IceBox)

    def __unicode__(self):
        return self.name

用于选择要删除的多个食品项目的表格:


class IceBoxEditForm(forms.Form):
        fooditems = forms.ModelChoiceField(queryset=FoodItem.objects.none(), widget=forms.CheckboxSelectMultiple(), empty_label=None)

相应的观点:


def icebox_edit(request, item=None):
        # Grab the particular icebox
        icebox = get_object_or_404(IceBox, pk=item)

        if request.method == "POST":
                form = IceBoxEditForm(request.POST)
                print request.POST
                if form.is_valid():
                        # Delete should happen
        else:
                form = IceBoxEditForm()
                # Only use the list of fooditems that this icebox holds
                form.fields['fooditems'].queryset = icebox.fooditem_set.all()

        return render_to_response('icebox_edit.html', {'form':form},context_instance=RequestContext(request))    

表单正确列出与该冰箱相关联的食品项目的复选框。但是,当我选择某个内容然后提交表单时,我会收到表单错误:

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

还有一些其他自定义验证我不知道Django期望吗?

编辑:我试过这个,但它会出现语法错误:


form:
class IceBoxEditForm(forms.Form):
        fooditems = forms.ModelChoiceField(queryset=FoodItem.objects.none(), widget=forms.CheckboxSelectMultiple(), empty_label=None)


        def __init__(self, *args, **kwargs):
              queryset = kwargs.pop('queryset', None)
              super(IceBoxEditForm, self).__init__(*args, **kwargs)

              if queryset:
                        self.fields['fooditems'].queryset = queryset

view:
        form = IceBoxEditForm(queryset=icebox.fooditem_set.all(), request.POST) # Syntax error!

        ....
    else:
        form = IceBoxEditForm(queryset=icebox.fooditem_set.all())
        ....

1 个答案:

答案 0 :(得分:3)

您已为GET请求更改了字段的查询集,但没有更改POST。因此,当您提交表单时,Django仍在使用原始查询集,因此您的选择无效。

要么在视图的开头更改它,那么POST和GET都会发生,或者甚至更好地使用__init__形式的方法。