2

我想允许用户删除与特定模型相关的外键列表。

假设我们有这两个模型:


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())
        ....
4

1 回答 1

3

您已更改 GET 请求的字段的查询集,但没有更改 POST 的查询集。所以当你提交表单时,Django 还在使用原来的查询集,所以你的选择是无效的。

要么在视图的开头更改它,所以它发生在 POST 和 GET 中,或者更好地在表单的__init__方法中进行。

于 2012-05-28T18:38:44.790 回答