我想允许用户删除与特定模型相关的外键列表。
假设我们有这两个模型:
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())
....